NSMutableDictionary "unrecognized selector sent to instance" NSMutableDictionary“未识别的选择器发送到实例”

3
    -(void)saveDictionary:(int)counter
    {
        NSString *path=[[NSBundle mainBundle] pathForResource:@"Data" ofType:@"plist"];
        NSString *test = [NSString stringWithFormat:@"%d", counter];
        [theDictionary setObject:test forKey:@"Counter"]; <---- Error
        [theDictionary writeToFile:path atomically:YES];
    }

    - (void)applicationDidEnterBackground:(UIApplication *)application
    {
        [self saveDictionary:[_viewController counter]];
    }

错误:

-[NSCFString setObject:forKey:]: unrecognized selector sent to instance
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSCFString setObject:forKey:]: unrecognized selector sent to instance

我可以从plist中加载"Counter"的值。如果我想要保存相同关键字“Counter”的新值……出现错误。需要帮助,已经花费了几个小时。

再见

这是初始化theDictionary的代码:

-(void)initDictionary {
    if (theDictionary == nil) {
        NSString *path=[[NSBundle mainBundle] pathForResource:@"Data" ofType:@"plist"];
        theDictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
        theString = [theDictionary objectForKey:@"Counter"];
    }
}

我找到了!
theString = [[NSString alloc] initWithFormat:[theDictionary objectForKey:@"Counter"]];

感谢大家的支持!
6个回答

4
这是因为存储在theDictionary中的对象实际上是NSString,而NSString没有包含名为-setObject:forKey的方法。请检查代码中任何分配theDictionary的地方,并确保它实际上是一个NSMutableDictionary

3

检查初始化...你可以这样做。

NSMutableDictionary *dictoForSyncing = [[NSMutableArray alloc] init];


1

看起来theDictionary是一个字符串而不是NSMutableDictionary。它在哪里创建的?同时发生了什么事情?


0

这意味着'theDictionary'根本不是一个字典。很可能它早些时候被释放了,某个NSString取代了它。

你正在使用ARC吗?'theDictionary'定义在哪里。

你尝试过僵尸工具来跟踪这个问题吗?那应该会有所帮助。


0

看起来你的属性theDictionary实际上不是一个字典,而是一个字符串(NSString)。请问theDictionary定义在哪里?


0
NSMutableArray *myObjFromFile = ....;
NSMutableDictionary *tmpDictFromFile = 
  [[[myObjFromFile objectAtIndex:xx] mutableCopy]; mutableCopy];

[tmpDictFromFile setObject:"YOUR OBJECT"
                    forKey:"YOUR KEY"];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接