保存数据:
- (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为中心。知道为什么吗?
答案 0 :(得分:2)
最简单的方法是使用NSNumber
的{{3}}方法:
loadint = [[array objectAtIndex:0] intValue];
答案 1 :(得分:1)
您需要以下第二行:
loadint = [array objectAtIndex:0];
int score = [loadint intValue];
NSString *myString35 = [NSString stringWithFormat:@"%d", loadint];
如果您只保存一个值,则使用带有键的NSDictionary,以便您更容易标记要保存的值。
答案 2 :(得分:0)
CGPointMake定义为:
CGPoint CGPointMake(
float x,
float y
)
你正在使用GreenBlot.center.x,它可能是一个浮点数并将它作为一个int提供给NSNumber ....返回并查看变量的类型并更改为[NSNumber numberWithFloat:...]和lx = [[array objectAtIndex:1] floatValue];等等。适当的。
此外,您在编辑原始问题时创建了一个不同的问题。