Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:'
like image 484
Nurdin Avatar asked Jun 25 '15 18:06

Nurdin


2 Answers

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
like image 138
Sergey Kalinichenko Avatar answered Oct 05 '22 12:10

Sergey Kalinichenko


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

like image 33
marhs08 Avatar answered Oct 05 '22 12:10

marhs08