保存数据:
- (NSString *)dataFilePath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:kFilename];
}
- (void)applicationWillTerminate:(NSNotification *)notification
{
NSMutableArray *array = [[NSMutableArray alloc] init];
NSNumber *number = [NSNumber numberWithInt:points];
[array addObject:number];
[array writeToFile:[self dataFilePath] atomically:YES];
[array release];
}
读取数据: BestLabel.text 会显示高分。我收到警告:“赋值使指针从没有强制转换的整数”
-(void)LoadData{
BestLabel.center = CGPointMake(150,300);
NSString *filePath = [self dataFilePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:filePath];
loadint = [array objectAtIndex:0];
NSString *myString35 = [NSString stringWithFormat:@"%d", loadint];
BestLabel.text = myString35;
[array release];
}
}
我从中得到的示例代码可以毫无问题地保存和加载文本字段。我想我可以将字符串转换为 int,但这似乎没有必要。谢谢你的帮助!
编辑:
- (void)applicationWillTerminate:(NSNotification *)notification
{ NSMutableArray *array = [[NSMutableArray alloc] init];
if (points > highscore){
NSString *myString35 = [NSString stringWithFormat:@"%d", points];
[array addObject:myString35];
}else {
NSString *myString35 = [NSString stringWithFormat:@"%d", highscore];
[array addObject:myString35];
}
NSNumber *number = [NSNumber numberWithInt:GreenBlot.center.x];
[array addObject:number];
NSNumber *number2 = [NSNumber numberWithInt:GreenBlot.center.y];
[array addObject:number2];
现在加载:
NSString *filePath = [self dataFilePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:filePath];
BestLabel.text = [array objectAtIndex:0];
highscore = [[array objectAtIndex:0] intValue];
lx = [[array objectAtIndex:1] intValue];
ly = [[array objectAtIndex:2] intValue];
GreenBlot.center = CGPointMake( lx,ly);
[array release];
}
lx 和 ly 是整数。我首先尝试了 CGPointMake( [[array objectAtIndex:1] intValue], [[array objectAtIndex:2] intValue] )。同样的结果,GreenBlot 以 0,0 为中心。知道为什么吗?