Reputation: 2822
In this code from an array i am selecting a dictionary,modifying it and saving back in another array .but i dont know why at the second last line of this code ie where i am inserting the dict it is crashing (message sent to deallocated instance).how can i fix this
NSArray *array=[NSArray arrayWithContentsOfFile:plistPath];
NSLog(@"array before %@",array);
NSMutableArray *tempArray=[[NSMutableArray alloc]init];
tempArray=(NSMutableArray*)array;
NSMutableDictionary *dictToBeChanged=[[NSMutableDictionary alloc]init];
dictToBeChanged=[tempArray objectAtIndex:indexPath.row];
[dictToBeChanged setObject:[NSNumber numberWithBool:YES] forKey:@"isPaid"];
[tempArray removeObjectAtIndex:indexPath.row];
[tempArray insertObject:dictToBeChanged atIndex:indexPath.row];
NSLog(@"array after %@",tempArray);
Upvotes: 0
Views: 123
Reputation: 9544
You are looking at a memory management issue. Try this:
NSMutableArray *array = [NSMutableArray arrayWithContentsOfFile:plistPath];//Temp array is unecessary
NSMutableDictionary *dictToBeChanged; //No need to allocate a new instance
Not directly related but:
Both of your alloc [init] calls are unnecessary and causing leaks. Basically what you are doing is creating a new blank array with the allocation and and assigning it to a variable. Then you immediately assign your variable to another array, losing the reference to the blank array/dictionary you just created, which means it can't get released. If you are calling release later in your code it will cause trouble.
Upvotes: 1
Reputation: 7133
When you assign array
to tempArray
you don't make it mutable just because you cast it.
It's an NSArray
, so you can't add/remove its objects.
Also, there are a few unneeded initializations (of tempArray and dictToBeChanged) since you're overwriting those variables with something else right after initializing (thus creating leaks).
What you need is probably something like this:
NSMutableArray *array = [NSMutableArray arrayWithContentsOfFile:plistPath];
NSMutableDictionary *dictToBeChanged = [[[array objectAtIndex:indexPath.row] mutableCopy] autorelease];
[dictToBeChanged setObject:[NSNumber numberWithBool:YES] forKey:@"isPaid"];
[array replaceObjectAtIndex:indexPath.row withObject:dictToBeChanged];
Note that this code doesn't do any validations on the contents of your plist.
Upvotes: 2
Reputation: 2719
try this
NSMutableArray *temp;
temp=[temp arrayByAddingObjectsFromArray:(NSArray *)otherArray];
Upvotes: 1
Reputation: 10393
You may want to add the objects to tempArray as the temparray
as follows:
[tempArray addObjectsFromArray:array];
Upvotes: 1