How to read point coordinates from a file with Objective-C?

563 views Asked by At

I have a file like this:

1.0 1.0
2.0 2.0
-3.0 2.0

each line is the coordinate of a point.

I don't know how to write a code to do following thing: read these coordinates from the file, convert them into double and store them in an array as NSPoint.

BTW, I tried to write Objective-C++, but it seems that ifstream does not work, which is a bug of XCode.

1

There are 1 answers

1
Anoop Vaidya On

Do this way:

NOTE: You can not store NSPoint in NSArray as all collection classes need obj-c objets to store and NSPoint is struct. So you need to convert it into NSValue.

NSString *yourPath=[@"~/Desktop/myFile.txt" stringByExpandingTildeInPath];
NSFileHandle *inFile = [NSFileHandle fileHandleForReadingAtPath:yourPath];
NSData  *myData=[inFile readDataToEndOfFile];

NSString *myText=[[NSString alloc]initWithData:myData encoding:NSASCIIStringEncoding];

NSArray *values = [myText componentsSeparatedByString:@"\n"];

NSMutableArray *points=[NSMutableArray new];
for (NSString *string in values) {
    NSArray *lines=[string componentsSeparatedByString:@" "];
    NSPoint point=NSMakePoint([lines[0]floatValue], [lines[1]floatValue]);
    points[points.count]=[NSValue valueWithPoint:point];
}


for (NSValue *value in points) {
    NSLog(@"->%@",value);
}