問題描述
NSMutableArray removeObjectAtIndex 在第二次執行時崩潰 (NSMutableArray removeObjectAtIndex crashes on second execution)
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?
‑‑‑‑‑
參考解法
方法 1:
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.
方法 2:
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"]];
方法 3:
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
(by PonySlays、hukir、Ramy Kfoury、sunkehappy)