How to create an NSMutableArray and assign a specific object to it?

novicePrgrmr picture novicePrgrmr · Sep 3, 2013 · Viewed 61.6k times · Source

I am just getting into Obj C, and I am looking to create an array of MKAnnotations.

I have already created the MKAnnotation class called TruckLocation that contains the name, description, latitude, and longitude.

Here is what I have so far for the array:

NSMutableArray* trucksArray =[NSMutableArray arrayWithObjects: @[<#objects, ...#>]  nil];

Answer

Wain picture Wain · Sep 3, 2013

Yore trying to combine 2 different syntaxes for similar but different things. You also don't seem to have any instances of your annotations.

Create some instances

TruckLocation *a1 = ...;
TruckLocation *a2 = ...;

Then we can add them

NSMutableArray *trucksArray = [NSMutableArray arrayWithObjects:a1, a2, nil];

Or

NSMutableArray *trucksArray = [@[a1, a2] mutableCopy]

This is a shorter and more modern form but you need to make it mutable as it will create an immutable instance.