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:'
答案 0 :(得分:15)
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
答案 1 :(得分:3)
You can't add objects into NSArray. Use NSMutableArray instead :)
答案 2 :(得分:2)
Your array cant be changed because is defined as NSArray
which is inmutable (you can't add or remove elements) Convert it to a NSMutableArray
using this
NSMutableArray *mutableShoppingList = [NSMutableArray arrayWithArray:shoppingList];
Then you can do
[mutableShoppingList addObject:flour];
答案 3 :(得分:1)