objective c - Adding a NSDictionary to a NSArray duplicates the first NSDictionary every time -
so pulled json
data web service stored in nsarray
called _infofromjson
. each array element in _infofromjson
has dictionary of key/value pairs. goal add them 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] ; };
with above code sort of achieved it, keeps adding same 1st dictionary myvehicleobject
, inserts same nsdictionary
4 times in past have used this:
[self.myvehicleobject addobject:[vehicleinmembersprofile copy]] ;
when it throws following exception:
*** terminating app due uncaught exception 'nsinvalidargumentexception', reason: '-[myvehicleobject copywithzone:]: unrecognized selector sent instance 0xab4e130'
what doing wrong here? thanks!
update requested sample 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; }
this may or may not related problem, forin
loop broken. whether or not incorrect usage actual cause of problem, should fix can nothing cause problems.
if want use indexofobject:
grab object @ index of array you're iterating through, should use regular for
loop:
for (int carcount=0; index < [_infofromjson count]; ++carcount) { // loop body remains identical have... // except remove carcount++; }
but you're doing, forin
loop indeed better, , forin
loops can faster since can handled in batches. if you're using forin
loop, use object you're defining in loop declaration:
for(nsdictionary* mydictionary in _infofromjson) { // mydictionary reference object in _infofromjson, //for whatever given index working on myvehicleobject *vehicleinmembersprofile = [[myvehicleobject alloc] init]; vehicleinmembersprofile.make = mydictionary[@"make"]; vehicleinmembersprofile.carname = mydictionary[@"nickname"]; vehicleinmembersprofile.year = mydictionary[@"year"]; [self.myvehicleobject addobject:vehicleinmembersprofile]; }
Comments
Post a Comment