0

I have a tableview with a number of rows that I want to be able to delete. The data that populates the tableview is stored in an NSMutableArray. To delete the data on one row I call:

- (void)deleteFromArray:(NSUInteger) number{
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];  //load NSUserDefaults
    NSMutableArray *storedArray = [[ NSMutableArray alloc] init];
    storedArray = [prefs objectForKey: @"mydata"];
    [storedArray removeObjectAtIndex:number];

    [prefs setObject:storedArray forKey:@"mydata"];
    [storedArray release];
    [prefs synchronize];

}

From

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        subscribe *subscribeclass = [subscribe alloc];
        [subscribeclass deleteFromArray: indexPath.row];
        [myTableView reloadData];
    }
}

This works fine the first time I delete a row. But when I delete a seconds row the application crashes on the following line in deleteFromArray:

[storedArray removeObjectAtIndex:number];

Any ideas why?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
PonySlays
  • 37
  • 4

3 Answers3

5

The array coming from your NSUserDefaults is a NSArray, not an NSMutableArray. You should modify your code to be like this:

- (void)deleteFromArray:(NSUInteger) number{
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];  //load NSUserDefaults
    NSMutableArray *storedArray = [[prefs objectForKey:@"mydata"] mutableCopy];
    [storedArray removeObjectAtIndex:number];

    [prefs setObject:storedArray forKey:@"mydata"];
    [storedArray release];
    [prefs synchronize];
}

This creates a copy of the immutable array and makes it mutable, so that you can modify it.

hukir
  • 1,733
  • 1
  • 9
  • 13
1

The things you can only store immutable NSArrays in defaults. Even if the object is mutable, it is stored as immutable

So instead of

 NSMutableArray *storedArray = [[ NSMutableArray alloc] init];
 storedArray = [prefs objectForKey: @"mydata"];

try:

 [NSMutableArray arrayWithArray:[prefs objectForKey: @"mydata"]];
Ramy Kfoury
  • 937
  • 5
  • 8
0

The problem is that the array returned from objectForKey is immutable. So you can see what other people do:Storing custom objects in an NSMutableArray in NSUserDefaults

Community
  • 1
  • 1
sunkehappy
  • 8,970
  • 5
  • 44
  • 65