我得到了与以下两个函数相关的大量EXC_BAD_ACCESS错误,用于读取和写入plist文件。我认为它的记忆力相关。有什么建议吗?
+(NSString *) getSettingString: (NSString *)key defaultValue:(NSString *)defValue
{
NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[pathArray objectAtIndex:0] stringByAppendingFormat:@"FSSettings_v3.plist"];
[pathArray release];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:path];
if (fileExists == YES) {
NSMutableDictionary* plistDictionary = [NSMutableDictionary dictionaryWithContentsOfFile:path];
NSString *value = [plistDictionary objectForKey:key];
return value;
} else {
[self setSettingString:key value:defValue];
return defValue;
}
}
+(void) setSettingString: (NSString *)key value:(NSString *)value
{
NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[pathArray objectAtIndex:0] stringByAppendingFormat:@"FSSettings_v3.plist"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:path];
if (fileExists == YES) {
NSMutableDictionary* plistDictionary = [NSMutableDictionary dictionaryWithContentsOfFile:path];
[plistDictionary setObject:value forKey:key];
[plistDictionary writeToFile:path atomically:YES];
[plistDictionary release];
} else {
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:value forKey:key];
[dict writeToFile:path atomically:YES];
[dict release];
}
[pathArray release];
}
答案 0 :(得分:2)
您不应该在第一种方法中发布pathArray
:
NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[pathArray objectAtIndex:0] stringByAppendingFormat:@"FSSettings_v3.plist"];
[pathArray release];
NSSearchNSSearchPathForDirectoriesInDomains
返回一个自动释放的对象。
始终在XCode中进行“构建和分析”。它会告诉你许多保留/释放问题。
那就是说,不要重新发明轮子。您可以使用NSUserDefaults。您的代码变为四行:
+(NSString *) settingString: (NSString *)key defaultValue:(NSString *)defValue
{
NSString*v=[[NSUserDefaults standardUserDefaults] stringForKey:key];
if(v){
return v;
}else{
return defValue;
}
}
+(void) setSettingString: (NSString *)key value:(NSString *)value
{
[[NSUserDefaults standardUserDefaults] setObject:value forKey:key]
}
我会使用registerDefaults:
向NSUserDefaults
注册默认值,而不是将其提供给-getSettingString
。
最后,您不应将get
放在getter的名称中。这违背了Objective-C的习惯。
在Objective-C中,get
通常仅在通过作为方法参数传入的指针返回结果时使用,如-[NSData getBytes:length:]
中所示。