ios - replace a object in NSMutableArray -


i try replace object array string. 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 try replace, app crash.

edit: logged "index". become integer 2147483647.

probably because call indexofobject returns nsnotfound.

nsnotfound constant tells oldstring object not found in self.myarray dictionary, , constant has value of (nsuinteger)-1 (which equivalent unsigned value 2147483647 because of integer underflow), value crash app "out of bounds" exception.

the solution test whether index != nsnotfound before using it. or make sure array self.myarray contains object of type nsstring value "oldobject".

if, given actual code, expected oldobject present in self.myarray, think again, maybe log content of self.myarray lookup contains, , check content string.
(if see "oldobject" when logging content of myarray, that's description string of object in array, array not contain string "oldobject" itself, object description "oldobject")


side note: there no need use stringwithformat if don't use format placeholder (like %d or %@ etc). should directly use string constant in case, no need dynamically build string if string constant: use nsstring* oldstring = @"oldobject" , nsstring* toreplace = @"newobject".


Comments

Popular posts from this blog

c# - Better 64-bit byte array hash -

webrtc - Which ICE candidate am I using and why? -

php - Zend Framework / Skeleton-Application / Composer install issue -