Pergunta

I've more experience with Python than anything else, so to work with mutable vs. immutable arrays and dicts is a little weird. I'm really enjoying the literal syntax that Xcode 4.5 has added, but in doing some simple messing about I come across a situation like this:

NSArray *myArray = [@[/*array objects here*/] mutableCopy];
[myArray addObject: @/*an object goes here*/];

and the compiler gives me a warning, stating "myArray may not respond to addObject".

The code compiles and addObject works just fine, I can NSLog the object and verify it exists in myArray - but I don't fully understand the nature of this warning. Does mutableCopy not return an NSMutableArray in this situation? Is it more appropriate to simply use NSMutableArray and not dink around with trying to (over)use literal syntax?

Also, since it's just a silly warning, can I ignore it and carry on? That seems... lazy at worst, and maybe just opens the door to shenanigans in the future.

Foi útil?

Solução

You need to declare your variable as NSMutableArray, not NSArray. addObject: is a method only available on NSMutableArray.

EDIT: You also seem to have an unnecessary @ in there. Your code should be:

NSMutableArray *mutable = [@[a, b, c] mutableCopy];
[mutable addObject:d];

Outras dicas

Does mutableCopy not return an NSMutableArray in this situation?

It does. That's why you have to assign the return value to an NSMutableArray, and not an NSArray.

NSMutableArray *myArray = [@[/*array objects here*/] mutableCopy];

should make the compiler shut up.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top