burrGGG
burrGGG

Reputation: 617

Save and load NSMutableArray - NSUserDefaults

I am trying to save a NSMutableArray to NSUserDefaults then reload it and use it to populate the button labels. Can someone please take a look and tell me what i am doing wrong here?

When I am loading the file to new array it appears empty. All of the buttons I am trying to set the titles to are in ibCollectionOutlet called buttons

-(void)save {
    [[NSUserDefaults standardUserDefaults] setObject:self.pressCountArray forKey:@"savedFile"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

-(void)load{

    NSMutableArray *countArray = [[[NSUserDefaults standardUserDefaults] arrayForKey:@"savedFile"] mutableCopy];

    for (NSInteger i = 0; i < [self.pressCountArray count]; i++){
        self.pressCountArray[i] = countArray[i];
    }

    for (NSInteger i = 0; i < [self.buttons count]; i++){
        UIButton *btn = self.buttons[i];
        int curCnt = [[self.pressCountArray objectAtIndex:i] integerValue];

        [btn setTitle:[NSString stringWithFormat:@"%i",curCnt] forState:UIControlStateNormal];
    }
}

Upvotes: 1

Views: 269

Answers (2)

trojanfoe
trojanfoe

Reputation: 122381

It looks like you are not allocating self.pressCountArray during the load and are probably attempting to populate an empty array (in a fairly strange way). Instead simply do:

-(void)load{

    self.pressCountArray = [[[NSUserDefaults standardUserDefaults] arrayForKey:@"savedFile"] mutableCopy];

    NSAssert([self.pressCountArray count] == [self.buttons count], @"Array count mismatch");

    for (NSInteger i = 0; i < [self.buttons count]; i++){
        UIButton *btn = self.buttons[i];
        int curCnt = [[self.pressCountArray objectAtIndex:i] integerValue];

        [btn setTitle:[NSString stringWithFormat:@"%i",curCnt] forState:UIControlStateNormal];
    }
}

Note that you need to check that the correct number of array elements have been loaded. I've used an NSAssert in the above code, but you probably need to return NO given it's probably something that can happen in production.

Upvotes: 0

Midhun MP
Midhun MP

Reputation: 107121

I think your array contains custom objects. If that is the case then you should implement NSCoding protocol (for serialization and de-serialization) in your custom model class.

Implement the following NSCoding protocol methods in your class:

- (void)encodeWithCoder:(NSCoder *)encoder;
- (id)initWithCoder:(NSCoder *)decoder;

After that save the data like:

NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:self.pressCountArray];
[[NSUserDefaults standardUserDefaults] setObject:encodedObject forKey:[NSString stringWithFormat:@"savedFile"]];

And retrieve the data like:

NSData *encodedObject = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"savedFile"]];
self.pressCountArray  = [NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];

Upvotes: 4

Related Questions