Reputation: 1225
I try 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 will crash.
Edit: I logged the "index". I will become a Integer like 2147483647
.
Upvotes: 3
Views: 130
Reputation: 32681
Probably because your call to indexOfObject
returns NSNotFound
.
NSNotFound
is a constant that tells you that the oldString
object is not found in your self.myArray
dictionary, and as this constant has a value of (NSUInteger)-1
(which is equivalent to the unsigned value 2147483647
because of integer underflow), value that will obviously crash your app with an "Out of Bounds" exception.
The solution is to test whether the index != NSNotFound
before using it. Or to make sure that your array self.myArray
actually contains an object of type NSString
whose value is "oldObject"
.
If, given your actual code, you expected oldObject
to be present in your self.myArray
, then think again, maybe log the content of self.myArray
to lookup what it actually contains, and also check that this content is a string.
(if you see "oldObject"
when logging the content of your myArray
, that's probably just the description
string of the object in your array, so the array does not contain the string "oldObject"
itself, but an object whose description is "oldObject"
)
Side note: there is no need to use stringWithFormat
if you don't use any format placeholder (like %d
or %@
etc). You should simply directly use the string constant in that case, no need to dynamically build a string if that string is a constant: simply use NSString* oldString = @"oldObject"
and NSString* toReplace = @"newObject"
.
Upvotes: 4