繁体   English   中英

使用initWithContentsOfFile创建的NSMutableDictionary的setValue方法中的错误访问错误iOS目标C

[英]Bad Access Error in setValue method for a NSMutableDictionary created with initWithContentsOfFile iOS Objective C

我在遵循Objective C Code时遇到问题:

要为我的应用程序读取配置plist,我创建了load和一个save Config方法,但是在将一个plist正确加载到(新分配的)NSMutableDictionary之后,我无法更改任何序列化项目,因为它似乎是一个错误的访问错误由错误的内存访问创建。 重点是我创建了一个新的NSMutableDictionary并将其作为loadConfig方法的结果返回。 如果我调试代码,则会正确创建Dictionary并且其中包含两个项/键对。 现在,当我尝试使用setValue(或setObject)更改Value时,我在CFRetain中遇到错误访问错误。

我究竟做错了什么?

我的代码:

访问加载的配置字典:

OBJCHelpers* objcHelpers = [OBJCHelpers alloc];
NSMutableDictionary* dictSettings = [objcHelpers loadConfig:@"configSettings"]; //Debugged here shows a correct Dictionary in 
//dictSettings with following two key/value pairs:
// Key: @"SourceSetting" Value: (int)0
// Key: @"DetectionSetting" Value: (int)0
[dictSettings setObject:(int)srcsetNew forKey:@"SourceSetting"]; //Here the crash happens (btw (int)srcsetNew returns in the debugger (int)2 so thats also not the problem)
[dictSettings setObject:(int)detectionsetNew forKey:@"DetectionSetting"];

加载Config的功能(它确实将配置文件作为字典返回,在Debugger中检查):

- (NSMutableDictionary*)loadConfig : (NSString*) nstrConfigPlistName {
    NSArray* nsarraySystemPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* nsstrDocumentsFolder = [nsarraySystemPaths lastObject];
    NSFileManager *fileManager = [NSFileManager defaultManager];

    NSString *nsstrConfigPlistFileName = [nstrConfigPlistName stringByAppendingString:@".plist"];
    NSString *nsstrPlistStartConfigFile = [[NSBundle mainBundle] pathForResource:nstrConfigPlistName ofType:@"plist"];
    NSString *nstrConfigPlistFile = [nsstrDocumentsFolder stringByAppendingPathComponent:nsstrConfigPlistFileName];

    if ((![fileManager fileExistsAtPath:nstrConfigPlistFile]) || cboolForcedConfigOverwrite) {
        if (![fileManager fileExistsAtPath:nsstrPlistStartConfigFile]) return [NSMutableDictionary alloc];
        else {
            NSError* error;
            if ([fileManager fileExistsAtPath:nstrConfigPlistFile]) [fileManager removeItemAtPath:nstrConfigPlistFile error:NULL];
            if (![fileManager copyItemAtPath:nsstrPlistStartConfigFile toPath:nstrConfigPlistFile error:&error])
                NSLog(@"Fehler beim kopieren in den Documents Folder : %@ !", [error localizedDescription]);
        }
    }

    return [[NSMutableDictionary alloc] initWithContentsOfFile:nstrConfigPlistFile];
}

无法使用retain返回NSMutableDictionary或使用initWithDictionary将其复制到新的Dictionary:[...] copyItems:true帮助。

请提前帮助,谢谢

如果srcsetNew是一个int ,你应该这样做:

[dictSettings setObject:@(srcsetNew) forKey:@"SourceSetting"];

以便将int转换为NSNumber实例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM