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:'
3
  • 4
    Use NSMutableArray instead because is dynamic Commented Jun 25, 2015 at 18:33
  • possible duplicate of NSArray adding elements Commented Jun 25, 2015 at 21:12
  • NSMutableArray *imageArray; imageArray =[[NSMutableArray alloc]init]; [imageArray addObject:imagename]; Commented Sep 19, 2017 at 10:19

4 Answers 4

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
Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

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];

1 Comment

Um, [NSMutableArray shoppingList]? Looks like your code is missing something.
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];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.