Reputation: 23883
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:'
Upvotes: 6
Views: 25546
Reputation: 68400
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];
Upvotes: 2
Reputation: 2206
NSArray
does not have addObject:
method, for this you have to use
NSMutableArray
. NSMutableArray
is used to create dynamic array.
NSArray *shoppingList = @[@"Eggs", @"Milk"];
NSString *flour = @"Flour";
NSMutableArray *mutableShoppingList = [NSMutableArray arrayWithArray: shoppingList];
[mutableShoppingList addObject:flour];
Or
NSMutableArray *shoppingList = [NSMutableArray arrayWithObjects:@"Eggs", @"Milk",nil];
NSString *flour = @"Flour";
[shoppingList addObject:flour];
Upvotes: 1
Reputation: 726579
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
Upvotes: 19