问题
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];
回答1:
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.
回答2:
Well:
NSString *a = @"a";
NSMutableArray *array = [NSMutableArray arrayWithObjects:a,nil];
//or
NSMutableArray *array = [[NSMutableArray alloc]init]; //alloc
[array addObject:a];
回答3:
NSMutableArray *array = [NSMutableArray alloc] init];
[array addObject:myObject];
Where myObject is the object of your custom class.
回答4:
Try something lke this
NSMutableArray *annotationArray=[[NSMutableArray alloc]init];
CLLocationCoordinate2D shopPosition = CLLocationCoordinate2DMake(allShopInfoObject.shopLatitudeValue, allShopInfoObject.shopLongitudeValue);
MapAnnotation *mapAnnotation = [[MapAnnotation alloc] initWithCoordinates:shopPosition andTitle:allShopInfoObject.shopName andShopId:allShopInfoObject.shopId subTitle:@""];
[annotationArray addObject:mapAnnotation];
[self.mapView addAnnotations:annotationArray];
回答5:
Suppose you initialize the objects and assign values the following way:
TruckLocation *truckLocationOne = [[TruckLocation alloc]initWithAnnotation:annotation
reuseIdentifier:annotationIdentifier];
truckLocationOne.name = @"name";
TruckLocation *truckLocationTwo = [[TruckLocation alloc]initWithAnnotation:annotation
reuseIdentifier:annotationIdentifier];
truckLocationTwo.name = @"name";
These objects would be added to the array temp in the following way:
1)
NSMutableArray temp = [[NSMtableArray alloc]initWithObjects:truckLocationOne,truckLocationTwo,nil];
2)
NSMutableArray temp = [[NSMtableArray alloc]init];
[temp addObject:truckLocationOne];
[temp addObject:truckLocationTwo];
Hope this answers your query
回答6:
TruckLocation *loc1=...;
TruckLocation *loc2=...;
NSMutableArray *truckArray=[[NSMutableArray alloc]initWithObjects:loc1,loc2];
you can add objects at the time of initialization. by this you can add objects within the allocation code. also you can avoid more number of steps for writing with addObject
.
来源:https://stackoverflow.com/questions/18600626/how-to-create-an-nsmutablearray-and-assign-a-specific-object-to-it