3

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.

2
  • 1
    2147483647 is NSNotFound. Where is myArray initialized and where is oldString added ? Commented Jul 5, 2015 at 16:47
  • BTW - get rid of the needless use of stringWithFormat:. Just do NSString *oldString = @"oldObject";. Commented Jul 5, 2015 at 16:56

1 Answer 1

4

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".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.