2013-05-27 41 views
1

我试图将分数(NSNumber)保存到plist文件中,然后加载它。 这是我保存方法:无法从plist加载数组,但没有获取对象

- (void)saveScore:(int)iScore; 
{ 
    NSMutableData *data = [[NSMutableData alloc] init]; 
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data]; 
    NSNumber *score=[NSNumber numberWithInt:iScore]; 

    [archiver encodeObject:[NSArray arrayWithObject:score]]; 
    [archiver finishEncoding]; 
    [data writeToFile:[self dataFilePath] atomically:YES]; 

} 

我检查,并在将数据保存到文件中。

这是我的加载方法:

-(void)LoadData{ 

    NSString *filePath = [self dataFilePath]; 
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) 
    { 
     NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:filePath]; 
     NSNumber * number= ((NSNumber *)[array objectAtIndex:0]); 
     int score=[number intValue]; 
    } 
} 

我检查和dataFilePath返回正确的道路。但阵列没有获得任何项目。

回答

3

如果使用NSKeyedArchiver创建一个文件,你需要使用一个NSKeyedUnarchiver读取该文件回。

如果你想使用[[NSMutableArray alloc] initWithContentsOfFile:...读取该文件中,那么你应该将数组保存到文件使用[data writeToFile:path atomically:YES];

+0

非常感谢你! –

相关问题