IOS - get NSDictionary from NSUserDefaults: tried to dereference an invalid ObjC object or send it an unrecognized selector

I am trying to restore NSMutableArrayfrom NSUserDefaultswhich were saved.

I save 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];

And try to restore NSMutableArray:

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

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

But, when I get access to tremp (param in a for loop), for example:

tremp.trempId

I get this error:

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

The process was returned to the state before evaluating the expression.

+4
source share
1 answer

When you save your object Trempby default, you actually save it as a dictionary.

, , 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;
    }
}

BTW - . , . for, .

, setValue:forKey: setObject:forKey:.

+3

Source: https://habr.com/ru/post/1525090/


All Articles