Search code examples
iosobjective-cnsarray

addObject to NSArray in Objective-C


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:'

Solution

  • 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