jjzjj

iOS - 从 NSUserDefaults :Attempted to dereference an invalid ObjC Object or send it an unrecognized selector 获取 NSDictionary

coder 2023-09-28 原文

我尝试从已保存的 NSUserDefaults 中检索 NSMutableArray

我存储 NSMutableArray:

NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
NSMutableArray* mySavedTremps = [[defaults objectForKey:UD_MY_TREMPS] mutableCopy];

if (!mySavedTremps)
        mySavedTremps =[[NSMutableArray alloc] init];

NSMutableDictionary* trempDict = NSMutableDictionary* trempDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"please", @"help", @"me" @"!", nil]
[trempDict setValue:trempId forKey:@"trempId"];
[mySavedTremps insertObject:trempDict atIndex:0];
[defaults setObject:mySavedTremps forKey:UD_MY_TREMPS];

[defaults synchronize];

并尝试检索 NSMutableArray:

NSMutableArray* myTrempsArray = [NSMutableArray arrayWithArray:[defaults objectForKey:UD_MY_TREMPS]];

for (Tremp* tremp in myTrempsArray) {        
        if([tremp.trempId isEqualToString:@"1234"]) {
            [myTrempsArray removeObject:tremp];
            break;
        }
    }

但是,当我像这样访问 tremp(for 循环中的参数)时:

tremp.trempId

我收到这个错误:

error: Execution was interrupted, reason: Attempted to dereference an invalid ObjC Object or send it an unrecognized selector.

进程已经返回到表达式求值前的状态。

最佳答案

当您将 Tremp 对象保存为默认值时,实际上是将其保存为字典。

但是当您读出它时,您的代码假定您有一个 Tremp 对象数组。

你想要这样的东西:

for (NSDictionary *trempDict in myTrempsArray) {
    Tremp *tremp = ... // add code here to create a Tremp from the dictionary
    if([tremp.trempId isEqualToString:@"1234"]) {
        [myTrempsArray removeObject:tremp];
        break;
    }
}

顺便说一句——这段代码会崩溃。您不能修改正在快速枚举的数组。将循环更改为标准的 for 循环,但反向执行循环。

此外,当您保存数据时,将对 setValue:forKey: 的调用替换为 setObject:forKey:

关于iOS - 从 NSUserDefaults :Attempted to dereference an invalid ObjC Object or send it an unrecognized selector 获取 NSDictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21533743/

有关iOS - 从 NSUserDefaults :Attempted to dereference an invalid ObjC Object or send it an unrecognized selector 获取 NSDictionary的更多相关文章

随机推荐