Alec
Alec

Reputation: 483

Change the content of a string within an array of strings

This is my code:

NSString *newString = @"new value"; 


[breakdownCollection objectAtIndex:i] = newString; 

breakdownCollection is an NSArray of multiple strings. I need to access a given string contained in the array via index number, and change the string's content to that of the new string. Note that I cannot simply replace the string with the new one, I am only trying to replace its contents.

When I try to do this, however, I get an "lvalue required as left operand of assignment" error.

Any help with this issue would be very much appreciated!

Upvotes: 1

Views: 114

Answers (2)

user756245
user756245

Reputation:

The error you get is because you wrote the assignement instruction incorrectly. That is, you cannot assign newString to [breakdownCollection objectAtIndex:i]. Also, you won't be able to do it this way. Instead, in order to modify string object content, use NSMutableString, which provides methods to do so (NSString are immutable objects). So, for example you should try :

[[breakdownCollection objectAtIndex:i] setString:newString];

assuming you put NSMutableString into breakdownCollection.

PS : in order to change the object at the index i, you have to use NSMutableArray instead of NSArray, and then call :

[breakdownCollection replaceObjectAtIndex:i withObject:newString];

Good luck !

NSMutableString class reference

NSMutableArray class reference

Upvotes: 2

PengOne
PengOne

Reputation: 48398

Use an NSMutableArray instead and then you can use the method -replaceObjectAtIndex: withObject:

Upvotes: 1

Related Questions