gpt4 book ai didi

iphone - 从文本文件中读取 NSPoint

转载 作者:行者123 更新时间:2023-11-28 18:03:48 24 4
gpt4 key购买 nike

我将两个 CGPoints(在一个数组中)保存到 Documents 目录中的一个文本文件中。当我阅读文件时,这是我得到的:

NSPoint: {66.5, 87}, NSPoint: {198.5, 314.5}

如何得到这样的输出:

66.5 87
198.5 314.5

这是我的代码:

//save the coordinates of two points into a text file in the Documents directory
- (void)savePoints
{
//get Document directory's path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"POINTS.txt"];

//create an points array
NSMutableArray *points = [[NSMutableArray alloc] init];
[points addObject:[NSValue valueWithBytes:&fromPoint objCType:@encode(CGPoint)]]; //insert object at the end of the array
[points addObject:[NSValue valueWithBytes:&toPoint objCType:@encode(CGPoint)]];

//write points array to file
BOOL result = [NSKeyedArchiver archiveRootObject:points toFile:fullPath];
NSLog(@"Archival result: %d", result);
}

//read the file
-(void)getPoints
{
//get Document directory's path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"POINTS.txt"];

//read points array from file
NSMutableArray *points = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
NSString *str = [points componentsJoinedByString:@","];
NSLog(@"%@", str);
}

最佳答案

您有一行代码获取两点数组,然后将其转换为字符串:

NSString *str = [points componentsJoinedByString:@","];

这给了你:

NSPoint: {66.5, 87},NSPoint: {198.5, 314.5}

您恰好在 getPoints 方法中执行此操作,但如果您也在 savePoints 方法中执行此操作,您将获得相同的结果。您的问题与保存到文件或从文件中检索无关。这只是您希望如何从 points 数组中提取 CGPoint 值的问题。

所以,如果你想收回你的两点(我认为这是真正的意图),你可以这样做:

CGPoint fromPoint = [[points objectAtIndex:0] CGPointValue];
CGPoint toPoint = [[points objectAtIndex:1] CGPointValue];

或者您可以使用最新版本的编译器:

CGPoint fromPoint = [points[0] CGPointValue];
CGPoint toPoint = [points[1] CGPointValue];

或者你可以这样做:

for (NSValue *value in points)
{
CGPoint point = [value CGPointValue];
NSLog(@"point = %.1f, %.1f", point.x, point.y);
}

然后你可以用你的两点为所欲为。

关于iphone - 从文本文件中读取 NSPoint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16278434/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com