Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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];
like image 409
novicePrgrmr Avatar asked Sep 03 '13 20:09

novicePrgrmr


People also ask

How do I create an NSArray in Objective C?

Creating NSArray Objects Using Array Literals In addition to the provided initializers, such as initWithObjects: , you can create an NSArray object using an array literal. In Objective-C, the compiler generates code that makes an underlying call to the init(objects:count:) method.

What is difference between NSArray and NSMutableArray?

The primary difference between NSArray and NSMutableArray is that a mutable array can be changed/modified after it has been allocated and initialized, whereas an immutable array, NSArray , cannot.

What is NSMutableArray in Swift?

The NSMutableArray class declares the programmatic interface to objects that manage a modifiable array of objects. This class adds insertion and deletion operations to the basic array-handling behavior inherited from NSArray . NSMutableArray is “toll-free bridged” with its Core Foundation counterpart, CFMutableArray .

Is NSMutableArray thread safe?

In general, the collection classes (for example, NSMutableArray , NSMutableDictionary ) are not thread-safe when mutations are concerned. That is, if one or more threads are changing the same array, problems can occur.


2 Answers

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.

like image 173
Wain Avatar answered Oct 13 '22 00:10

Wain


Well:

NSString *a = @"a";
NSMutableArray *array = [NSMutableArray arrayWithObjects:a,nil];
//or
NSMutableArray *array = [[NSMutableArray alloc]init]; //alloc

[array addObject:a];
like image 22
oiledCode Avatar answered Oct 12 '22 23:10

oiledCode