6

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:'
halfer
  • 19,824
  • 17
  • 99
  • 186
Nurdin
  • 23,382
  • 43
  • 130
  • 308

4 Answers4

19

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
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
4

You can't add objects into NSArray. Use NSMutableArray instead :)

marhs08
  • 57
  • 1
  • 1
  • 6
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];
Claudio Redi
  • 67,454
  • 15
  • 130
  • 155
1

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];
Kirti Nikam
  • 2,166
  • 2
  • 22
  • 43