I have the following code running when the user clicks the "Save" button:
- (IBAction) onSaveChangesClick:(id)sender {
NSMutableString *newGroups = [[NSMutableString alloc] init];
for (int i = 0; i < [self.isInGroupArr count]; i++) {
if ([[self.isInGroupArr objectAtIndex:i] boolValue] == YES) {
[newGroups appendString:[[AppDelegate arrayGroups] objectAtIndex:i]];
[newGroups appendString:@","];
}
}
// remove last : ","
if ([newGroups length] > 0)
newGroups = [NSMutableString stringWithString:[newGroups substringToIndex:[newGroups length] - 1]];
self.contact.groups = newGroups;
[newGroups release];
//[[self navigationController] popViewControllerAnimated:YES];
}
self.IsInGroups
is BOOL
array and arrayGroups
is (NSString *) array
that holds groups names.
I would like to add the newGroups
string to the arrayGroups[i]
only if (IsInGroups[i] == YES)
.
This piece of code generates EXC_BAD_ACCESS
. WHY?
Thanks.
Here you create autoreleased instance of NSMutable string.
so you shouldn't release it, and all will be fine.
Here is improved code:
}
Explanation:
Here you allocate memory and retain it.
[[NSMutableString alloc] init]
[NSMutableString stringWithString: returns autoreleased instance of NSMutable string, that we shouldn't release(it does the same as [[[NSMutableString alloc] init] autorelease] + smth more). and you assign it to variable newGroups(so your old value that was stored in this variable lost)
if ([newGroups length] > 0) newGroups = [NSMutableString stringWithString:[newGroups substringToIndex:[newGroups length] - 1]];
newGroups here is autoreleased, you release it, and it destroys. But as it was autoreleased, autorelease pool tries to release it again and gets exception(because memory is allready free)
[newGroups release];