addObject to NSArray in Objective-C

时间:2015-06-25 18:31:00

标签: ios objective-c nsarray

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

4 个答案:

答案 0 :(得分:15)

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

答案 1 :(得分:3)

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

答案 2 :(得分: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];

答案 3 :(得分: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];