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

左心房为你撑大大i 提交于 2019-12-05 01:45:32
Wain

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.

elio.d

Well:

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

[array addObject:a];
NSMutableArray *array = [NSMutableArray alloc] init];
[array addObject:myObject];

Where myObject is the object of your custom class.

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];

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!