How to initialize an empty mutable array in Objective C
Solution 1
Update:
With new syntax you can use:
NSMutableArray *myArray = [NSMutableArray new];
Original answer:
for example:
NSMutableArray *myArray = [[NSMutableArray alloc] init];
And here you find out why (difference between class and instance method)
Solution 2
Basically, there are three options:
First
NSMutableArray *myMutableArray = [[NSMutableArray alloc] init];
Second
NSMutableArray *myMutableArray = [NSMutableArray new];
Third
NSMutableArray *myMutableArray = [NSMutableArray array];
Solution 3
You can also initialize in this way
Another way for Objective C apart from the answer of @NSSam
NSMutableArray *myMutableArray = [@[] mutableCopy];
For Swift
let myArray = NSMutableArray()
OR
let myArray = [].mutableCopy() as! NSMutableArray;
Solution 4
NSMutableArray *arr = [NSMutableArray array];
Solution 5
I use this way to initialize an empty mutable array in Objective C:
NSMutableArray * array = [NSMutableArray arrayWithCapacity:0];
crashprophet
I am completely new to programming, but I am trying to learn as quickly as possible. I have been and continue to be deeply invested in Apple, so I have begun by learning the Cocoa framework. I have two iOS applications in development. One is open source on GitHub and will hopefully track food trucks in Los Angeles better than other applications out there right now.
Updated on August 08, 2020Comments
-
crashprophet almost 4 years
I have a list of objects (trucks) with various attributes that populate a tableview. When you tap them they go to an individual truck page. There is an add button which will add them to the favorite list in another tableview. How do I initialize an empty mutable array in Cocoa?
I have the following code:
-(IBAction)addTruckToFavorites:(id)sender:(FavoritesViewController *)controller { [controller.listOfTrucks addObject: ((Truck_Tracker_AppAppDelegate *)[UIApplication sharedApplication].delegate).selectedTruck]; }
-
Nico about 12 yearsEven if the array is initially empty, if you know that you will be putting a certain number of objects into it,
initWithCapacity:
may make that population step faster (because the array may initially create its backing storage with space for that many objects). -
Nico about 12 yearsMoreover, autorelease is not the evil that some people make it out to be. There's nothing wrong with
[NSMutableArray array]
; it's just not appropriate for this case, assuming that the controller will assign the new array directly to its private_listOfTrucks
instance variable. -
saagarjha almost 6 yearsThis doesn't create a mutable array.