如何创build一个NSMutableArray并为其指定一个特定的对象?
我只是进入Obj C,我正在创build一个MKAnnotations数组。
我已经创build了名为TruckLocation
的MKAnnotation类,它包含名称,描述,纬度和经度。
这是我迄今为止的数组:
NSMutableArray* trucksArray =[NSMutableArray arrayWithObjects: @[<#objects, ...#>] nil];
总是试图将两种不同的语法结合起来,用于类似但不同的事情。 您似乎也没有任何注释的实例。
创build一些实例
TruckLocation *a1 = ...; TruckLocation *a2 = ...;
然后我们可以添加它们
NSMutableArray *trucksArray = [NSMutableArray arrayWithObjects:a1, a2, nil];
要么
NSMutableArray *trucksArray = [@[a1, a2] mutableCopy]
这是一个更短,更现代的forms,但你需要使它可变,因为它会创build一个不可变的实例。
好:
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];
其中myObject是您的自定义类的对象。
试试这个
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];
假设您初始化对象并按以下方式分配值:
TruckLocation *truckLocationOne = [[TruckLocation alloc]initWithAnnotation:annotation reuseIdentifier:annotationIdentifier]; truckLocationOne.name = @"name"; TruckLocation *truckLocationTwo = [[TruckLocation alloc]initWithAnnotation:annotation reuseIdentifier:annotationIdentifier]; truckLocationTwo.name = @"name";
这些对象将按以下方式添加到数组temp中:
1) NSMutableArray temp = [[NSMtableArray alloc]initWithObjects:truckLocationOne,truckLocationTwo,nil];
2) NSMutableArray temp = [[NSMtableArray alloc]init]; [temp addObject:truckLocationOne]; [temp addObject:truckLocationTwo];
NSMutableArray temp = [[NSMtableArray alloc]init]; [temp addObject:truckLocationOne]; [temp addObject:truckLocationTwo];
希望这回答您的查询
TruckLocation *loc1=...; TruckLocation *loc2=...; NSMutableArray *truckArray=[[NSMutableArray alloc]initWithObjects:loc1,loc2];
您可以在初始化时添加对象。 通过这个你可以在分配代码中添加对象。 还可以避免使用addObject
编写更多的步骤。