Reputation: 1182
I have a mutable array of strings. For this example, let's say there are 2 strings in it.
The operation that I would like to do is take the first string and assign the value of the second string to it.
I was trying something like this:
- (void) someAction {
NSMutableArray * array = [[NSMutableArray alloc] initWithObjects: string1, string2, nil];
NSString * firstString = [array objectAtIndex:0];
NSString * secondString = [array objectAtIndex:1];
firstString = secondString;
}
But this method doesn't seem to work. As after I log these two strings, they don't change after the operation.
Please advise.
Upvotes: 0
Views: 2254
Reputation: 40995
You can't change strings in an array like that.
The array contains pointers to the strings, and when you assign one string to another you are just swapping pointers around, not changing the string object that the array points to.
What you need to do to swap the string in the array is this:
- (void) someAction {
NSMutableArray * array = [[NSMutableArray alloc] initWithObjects: string1, string2, nil];
NSString * secondString = [array objectAtIndex:1];
[array replaceObjectAtIndex:0 withObject:secondString]; //replace first string with second string in the array
}
Upvotes: 7