简体   繁体   中英

Changing integer values in NSMutableArray, IOS Objective-C

I created an array that would hold some integers. However I seem to get an error on a line of code which is trying to alter one of the values in the array. I have created an array as follows:

NSMutableArray *lockedArray;
lockedArray = [NSMutableArray arrayWithCapacity:50];

I have added some values into the array:

[lockedArray addObject:@10];
[lockedArray addObject:@20];
[lockedArray addObject:@30];
[lockedArray addObject:@40];
[lockedArray addObject:@50];
[lockedArray addObject:@60];
[lockedArray addObject:@70];
[lockedArray addObject:@80];

Now I want to change one of the values. For example if I want to change the 6th value then I use the following code...

[lockedArray replaceObjectAtIndex:5 withObject:@1];

In Xcode I do not get any warning and it all looks fine. When I run the code and initiate replacing an object it crashes and gives me the following error...

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFArray replaceObjectAtIndex:withObject:]: mutating method sent to immutable object'

We don't know what you are doing exactly, but at the point where replaceObjectAtIndex is called, lockedArray is not a mutable array but an immutable array.

Since an array cannot be changed from being mutable to immutable, you most likely assigned a different (immutable) array to lockedArray after you added the other elements.

Have u allocated and initialized ur array like this,

lockedArray = [[NSMutableArray alloc]init];

Try it, Hope it will work for u

Make sure you check that you haven't pointed lockedArray to a non mutable array or you haven't initiated it as such. Use Xcode's find function to search for

"lockedArray = [NSArray"

or

"lockedArray ="

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM