Replace object in NSMutableArray
I am trying to replace an object from my array with a string. I use
@property (strong, nonatomic) NSMutableArray *myArray;
NSString *oldString = [NSString stringWithFormat:@"oldObject"];
NSString *toReplace = [NSString stringWithFormat:@"newObject"];
NSUInteger index = [self.myArray indexOfObject:oldString];
[self.firstLanguageArray replaceObjectAtIndex:index withObject:toReplace];
But every time I try to replace the app crashes.
Edit: I registered the "index". I will become Integer like 2147483647
.
source to share
Perhaps because your call indexOfObject
returns NSNotFound
.
NSNotFound
is a constant that tells you the object was oldString
not found in your dictionary self.myArray
, and since this constant has a value (NSUInteger)-1
(which is equivalent to an unsigned value 2147483647
due to an integer downstream), a value that will obviously crash your application with an exception " Out of bounds ".
The solution is to check if there is one index != NSNotFound
before using it. Or to make sure that your array self.myArray
actually contains an object of the type NSString
whose value is "oldObject"
.
If, given your actual code, you expected what oldObject
would be present in yours self.myArray
, then think again, perhaps register the content self.myArray
to look for what it actually contains, and also make sure the content is a string.
(if you see "oldObject"
when registering the contents of yours myArray
, probably only the strings of the description
object in your array, so the array does not contain a string "oldObject"
, but an object whose description is "oldObject"
)
Side note: not necessary to use stringWithFormat
unless you are using any format placeholder (like, %d
or %@
, etc.). You should just use a string constant in this case, no need to dynamically construct a string if that string is a constant: just use NSString* oldString = @"oldObject"
and NSString* toReplace = @"newObject"
.
source to share