IOS/Objective-C: 操作数组的维度

IOS/Objective-C: Manipulate dimensions of arrays

为了在 Core Data 中搜索两个实体,我想创建一个从两者中提取的数组。从一个实体创建一组对象很容易,也可以使用 valueforkey 创建一个只有一个属性的数组。您可以使用 arrayByAddingObjectsFromArray 将单个属性数组组合成一个长数组。但是,我需要从包含名称和 ID 的每个实体创建两个属性数组。

有谁知道像在 R 或许多其他语言中那样删除属性或字段的方法,这样我就可以创建仅包含两个属性的数组,然后将它们加在一起?

起始数组具有不同数量的属性,即

cars({
        make = "Ford";
        model = "Focus";
        year = "2010";
        carid = 127;
    },
        {
       make = "Chevy";
        model = "Camaro";
        year = "2014";
        carid = 126;
        })
 bikes({
        make = "Giant";
        year = "2010";
        bikeid = 33;
    },
        {
       make = "Trek";
        year = "2014";
        bikeid = 34;
        })

使用键的值,如:

NSMutableArray * carmakes = [[cars valueForKey:@"make"] mutableCopy];

我可以将数组转换为

cars(
    "Ford",
    "Chevy",
    "Toyota")

bikes(
    "Giant",
    "Trek",
    "Cannondale")

并使用:

vehicles=[_bikes arrayByAddingObjectsFromArray:_cars];

将这些合并为:

vehicles(
"Giant",
    "Ford",
    "Chevy",
    "Toyota",
    "Giant",
    "Trek",
    "Cannondale")

但是,没有id。我如何创建一个如下所示的数组:

vehicles({
        make = "Ford";
       id = 127;
    },
        {
       make = "Chevy";
        id = 126;
         },
        {
       make = "Giant";
        id = 33; },
        {
       make = "Trek";
        id = 34;})

编辑:

以下是属性在其托管对象文件中的显示方式:

@interface Cars : NSManagedObject
@property (nonatomic, retain) NSNumber * carid;
@property (nonatomic, retain) NSString * make;
@end

数组是通过以下代码创建的:

   NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Cars"];
    fetchRequest.resultType = NSDictionaryResultType;

    NSError *error      = nil;
    self.managedObjectContext = [Model sharedInstance].managedObjectContext;

    NSArray *results    = [self.managedObjectContext executeFetchRequest:fetchRequest
                                                                   error:&error];
    NSMutableArray* cars = [NSMutableArray arrayWithArray:results];

    return cars;

感谢您的任何建议。

不要想太多。创建一个方法来组合两个数组。

更新

从你得到的错误,我可以看出你没有字典数组,而是 CoreData 实体。在不知道游戏中的实体的情况下,这只是猜测。我将使用 CarsBikes,但 return 字典。您可能需要更新它才能使用 Vehicles 实体。

- (NSArray *)arrayByCombiningCars:(NSArray *)cars bikes:(NSArray *)bikes {
    NSMutableArray *result = [NSMutableArray arrayWithCapacity:cars.count + bikes.count];

    for (Cars *car in cars) {
        NSAssert(car.make && car.carid, @"car must have a make and cardid.");
        NSDictionary *vehicle = @{@"make":car.make, @"id": car.carid};
        [result addObject:vehicle];
    }

    for (Bikes *bike in bikes) {
        NSAssert(bike.make && bike.bikeid, @"bike must have a make and bikeid.");
        NSDictionary *vehicle = @{@"make":bike.make, @"id": bike.bikeid};
        [result addObject:vehicle];
    }

    return [result copy];
}