Domanda

So I use the following to alphabetically sort my NSMutableArray and it works great.

[myArray sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

But this is doing something to my array as I can't add to it after it crashes after the following line

[myArray addObject:textBox.text];

I get the following error

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

I know it has something do with the sorting function as this problem only occurs when I modify my mutable array! Can anyone understand why this is happening?

Not sure why its saying its an immutable object definitely a mutableArray I'm working with..

@property (strong, nonatomic) NSMutableArray *myArray;

Heres the rest of the code

@synthesize myArray;

myArray=[[NSMutableArray alloc] initWithObjects:@"numberOne",@"numberTwo",@"numberThree",@"numberFour",@"numberFive", nil];

NSUserDefault code

myUserDefault = [NSUserDefaults standardUserDefaults];
myArray = [myUserDefault objectForKey:@"stuff"];
[myUserDefault synchronize];
È stato utile?

Soluzione

@property (strong, nonatomic) NSMutableArray *speciesArray;

See my answer here:

https://stackoverflow.com/a/22748539/341994

And indeed, the facts are exactly the same. It is not enough to declare the class of something. That thing must actually be that class (polymorphism). An instance has a class (as an internal fact about it), quite without regard for how you may cast or declare a variable that merely refers to it.

You will thus find that, however you are actually making or obtaining this array, it is a non-mutable array (NSArray); merely claiming it is mutable, as you are doing, will not make it so. The facts have a power of their own.

EDIT: And so indeed it proved to be the case. You are say, in effect, this:

myArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"stuff"];

Now myArray is an immutable array, no matter how you declared myArray. The fix is to do a mutableCopy:

myArray = [[[NSUserDefaults standardUserDefaults] objectForKey:@"stuff"] mutableCopy];

Altri suggerimenti

when use NSUserDefaults, return array should be NSArray, not NSMutableArray:

myUserDefault = [NSUserDefaults standardUserDefaults];
myArray = [[NSMutableArray alloc] initWithArray:[myUserDefault objectForKey:@"stuff"]];
[myUserDefault synchronize];
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top