我已经使用此代码从plist加载数据。
-(void)loadOrCreateData {
NSLog(@"Start loadOrCreateData");
NSString *filePath = [self dataFilePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
NSLog(@"File Exists.. Loading from plist File");
NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
font = [array objectAtIndex:0];
background = (NSString *)[array objectAtIndex:1];
animation = [array objectAtIndex:5];
[array release];
NSLog(@"Loading Done!");
}
else
{
NSLog(@"File does not exist.. Creating new plist File");
font = @"Georgia-BoldItalic";
background = @"monalisa.jpeg";
animation = @"103";
[self saveData];
}
NSLog(@"Finish loadOrCreateData");
}
- (NSString *)dataFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:@"data.plist"];
}
- (void)saveData {
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:font];
[array addObject:background];
[array addObject:animation];
[array writeToFile:[self dataFilePath] atomically:YES];
[array release];
}
当没有plist文件从中获取数据时,第一次正常加载。但是在第二次加载时,当我尝试在loadOrCreate
方法之外使用加载的数据时,应用程序崩溃了。出于某种原因,在loadOrCreate
方法之外访问时,字体,背景和动画中的数据不可用。变量 -
字体,背景和动画在.h
文件中声明为NSStrings,因此应该是全局可用的吗?你能告诉我这是什么原因吗?
答案 0 :(得分:2)
您必须保留这些对象。
font = [[array objectAtIndex:0] retain];
background = (NSString *)[[array objectAtIndex:1] retain];
animation = [[array objectAtIndex:5] retain];
...
font = [@"Georgia-BoldItalic" retain];
background = [@"monalisa.jpeg" retain];
animation = [@"103" retain];
注意:如果您多次加载数据,请不要忘记在设置之前释放值。
编辑:
-(void)loadOrCreateData {
[font release];
[background release];
[animation release];
NSLog(@"Start loadOrCreateData");
NSString *filePath = [self dataFilePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
NSLog(@"File Exists.. Loading from plist File");
NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
font = [[array objectAtIndex:0] retain];
background = (NSString *)[[array objectAtIndex:1] retain];
animation = [[array objectAtIndex:5] retain];
[array release];
NSLog(@"Loading Done!");
}
else
{
NSLog(@"File does not exist.. Creating new plist File");
font = [@"Georgia-BoldItalic" retain];
background = [@"monalisa.jpeg" retain];
animation = [@"103" retain];
[self saveData];
}
NSLog(@"Finish loadOrCreateData");
}