Storing custom objects in an NSMutableArray in NSUserDefaults

后端 未结 5 1683
情深已故
情深已故 2020-11-22 16:11

I\'ve recently been trying to store the search results of my iPhone app in the NSUserDefaults collection. I also use this to save user registration info successfully, but fo

5条回答
  •  醉酒成梦
    2020-11-22 16:50

    For loading custom objects in an array, this is what I've used to grab the array:

    NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
    NSData *dataRepresentingSavedArray = [currentDefaults objectForKey:@"savedArray"];
    if (dataRepresentingSavedArray != nil)
    {
        NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingSavedArray];
        if (oldSavedArray != nil)
            objectArray = [[NSMutableArray alloc] initWithArray:oldSavedArray];
        else
            objectArray = [[NSMutableArray alloc] init];
    }
    

    You should check that the data returned from the user defaults is not nil, because I believe unarchiving from nil causes a crash.

    Archiving is simple, using the following code:

    [[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:objectArray] forKey:@"savedArray"];
    

    As f3lix pointed out, you need to make your custom object comply to the NSCoding protocol. Adding methods like the following should do the trick:

    - (void)encodeWithCoder:(NSCoder *)coder;
    {
        [coder encodeObject:label forKey:@"label"];
        [coder encodeInteger:numberID forKey:@"numberID"];
    }
    
    - (id)initWithCoder:(NSCoder *)coder;
    {
        self = [super init];
        if (self != nil)
        {
            label = [[coder decodeObjectForKey:@"label"] retain];
            numberID = [[coder decodeIntegerForKey:@"numberID"] retain];
        }   
        return self;
    }
    

提交回复
热议问题