How to addObject to NSArray using this code? I got this error message when trying to do it.
NSArray *shoppingList = @[@"Eggs", @"Milk"];
NSString *flour = @"Flour";
[shoppingList addObject:flour];
shoppingList += @["Baking Powder"]
Error message
/Users/xxxxx/Documents/iOS/xxxxx/main.m:54:23: No visible @interface for 'NSArray' declares the selector 'addObject:'
addObject
works on NSMutableArray
, not on NSArray
, which is immutable.
If you have control over the array that you create, make shoppingList
NSMutableArray
:
NSMutableArray *shoppingList = [@[@"Eggs", @"Milk"] mutableCopy];
[shoppingList addObject:flour]; // Works with NSMutableArray
Otherwise, use less efficient
shoppingList = [shoppingList arrayByAddingObject:flour]; // Makes a copy
You can't add objects into NSArray. Use NSMutableArray instead :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With