0

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.

  • 3
    You're getting a compiler warning because you assigned the NSMutableArray to an NSArray pointer. The compiler, taking you at your word, complains that NSArray does not implement `addObject`. – Hot Licks Oct 17 '12 at 18:26
  • Sadly I'm away from my laptop with Xcode; as I recall when I tried to assign the same code as an NSMutableArray I got a different error altogether, about how literals didn't jive with mutableArray. Hence the mutableCopy message. Maybe this has changed in the last update, or maybe I've overlooked something? –  Oct 17 '12 at 18:28
  • Right -- you weren't doing the `mutableCopy` call and so what you got from the literal was an NSArray. You cannot do `addObject` to an NSArray. You properly added the `mutableCopy` call but did not at the same time change the result data type to NSMutableArray, and that is your problem. – Hot Licks Oct 17 '12 at 18:30

2 Answers2

2

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];
Mike Weller
  • 45,401
  • 15
  • 131
  • 151
  • I was under the impression that literal syntax only worked for mutable lists, dicts, strings, etc. –  Oct 17 '12 at 18:25
  • -mutableCopy returns an NSMutableArray. You're not assigning the literal to the variable, you're assigning the mutable copy. – Catfish_Man Oct 17 '12 at 18:29
  • Yep, I was wondering about that `@` -- I've not yet used the literal syntax, so wasn't sure that it was an error. – Hot Licks Oct 17 '12 at 18:33
0

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.

jscs
  • 63,694
  • 13
  • 151
  • 195