NSMutableDictionary“无法识别的选择器发送到实例”

时间:2011-12-08 21:37:59

标签: iphone nsmutabledictionary

    -(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加载Key“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 个答案:

答案 0 :(得分:4)

这是因为theDictionary中存储的对象实际上是NSStringNSString不包含名为-setObject:forKey的方法。检查代码中是否有theDictionary被分配的地方,并确保其实际为NSMutableDictionary

答案 1 :(得分:3)

检查启动..你可以这样做。

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

答案 2 :(得分:1)

听起来像theDictionary是一个字符串而不是NSMutableDictionary。它在哪里被创造出来并且在此期间发生了什么?

答案 3 :(得分:0)

这说'theDictionary'根本就不是字典。很可能它早些时候发布了,一些NSString取而代之。

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

你有没有试过僵尸乐器跟踪这个?这应该会有所帮助。

答案 4 :(得分:0)

您的属性theDictionary实际上不是字典,而是字符串(NSString)。 theDictionary定义在哪里?

答案 5 :(得分:0)

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

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