将NSDictionary添加到NSArray每次都会复制第一个NSDictionary

log*_*ist 0 json objective-c nsdictionary nsarray

所以我JSON从一个存储在NSArray被叫中的Web服务中提取了一些数据_infoFromJSON.每个数组元素_infoFromJSON基本上都有一个键/值对的字典.目标是将它们添加到myVehicleObject其中NSMutableArray

for (NSDictionary* myDictionary in _infoFromJSON) {
    myVehicleObject *vehicleInMembersProfile;
    vehicleInMembersProfile = [[myVehicleObject alloc] init];
    vehicleInMembersProfile.make = [[_infoFromJSON objectAtIndex:carCount] objectForKey:@"make"];
    vehicleInMembersProfile.carName = [[_infoFromJSON objectAtIndex:carCount] objectForKey:@"nickname"];
    vehicleInMembersProfile.year = [[_infoFromJSON objectAtIndex:carCount] objectForKey:@"year"];
    carCount ++;
    [self.myVehicleObject addObject:vehicleInMembersProfile] ;
};
Run Code Online (Sandbox Code Playgroud)

使用上面的代码我有点实现它,但它不断添加相同的第一个字典myVehicleObject,所以它插入相同的NSDictionary4次过去我使用过:

[self.myVehicleObject addObject:[vehicleInMembersProfile copy]] ;
Run Code Online (Sandbox Code Playgroud)

当我这样做时,它抛出以下异常:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[myVehicleObject copyWithZone:]: unrecognized selector sent to instance 0xab4e130'
Run Code Online (Sandbox Code Playgroud)

我在这做错了什么?谢谢!

更新请求的示例JSON:

{
        color = SILVER;
        engine = "";
        id = "CF270B81-3821-4585-8C90-7089D7A8654E";
        imageUrl = "https://www.someprotectedurl.com/somefile.png";
        licensePlate = "ABC-123";
        make = Honda;
        model = "CR-V";
        nickname = "My CR-V";
        vin = "XX551234687687687654";
        year = 2009;
    }
Run Code Online (Sandbox Code Playgroud)

nhg*_*rif 6

这可能与问题有关,也可能与此无关,但您的forin循环完全被破坏了.无论您的错误使用是否是问题的实际原因,这是您应该确定的事情,因为它只会导致问题.

如果你想使用indexOfObject:在你正在迭代的数组的索引处获取一个对象,你应该使用一个常规for循环:

for (int carCount=0; index < [_infoFromJSON count]; ++carCount) {
    // loop body remains identical to what you have... 
    // except remove carCount++;
}
Run Code Online (Sandbox Code Playgroud)

但是对于你正在做的事情,forin循环确实更好,并且forin循环可以更快,因为它们可以批量处理.但是,如果您正在使用forin循环,请使用您在循环声明中定义的对象:

for(NSDictionary* myDictionary in _infoFromJSON) {
    // myDictionary is a reference to an object in _infoFromJSON, 
    //for whatever given index it is currently working on

    myVehicleObject *vehicleInMembersProfile = [[myVehicleObject alloc] init];
    vehicleInMembersProfile.make = myDictionary[@"make"];
    vehicleInMembersProfile.carName = myDictionary[@"nickname"];
    vehicleInMembersProfile.year = myDictionary[@"year"];
    [self.myVehicleObject addObject:vehicleInMembersProfile];
}
Run Code Online (Sandbox Code Playgroud)