iphone - Can't update an NSMutableDictionary value from within a for-in loop? -
i'm having weird issue updating nsmutabledictionary value. i'm running for-in loop, retrieved fine, , math fine.
the problem lies when try update dictionary setvalue: forkey:
method.
for(nsstring *key in self.planetdictionary){ if(![key isequaltostring:planet]){ * * * //do math , stuff, create nsnumber: nsnumber *update = [nsnumber numberwithfloat:updatedprobability]; //problem code, exc_bad_access here: [self.planetdictionary setvalue:update forkey:key]; } }
i exc_bad_access crashes. can confirm else fine, single line try update value.
what's going on? thanks
you're not allowed mutate object you're fast enumerating. crash every time. work around, can make copy first:
nsdictionary *dictionary = [self.planetdictionary copy]; (nsstring *key in dictionary) { if (![key isequaltostring:planet]) { nsnumber *update = [nsnumber numberwithfloat:updatedprobability]; [self.planetdictionary setvalue:update forkey:key]; } }
alternatively, if have large objects in dictionary (that conform nscopying
, or else shallow copy , won't matter much), , hence don't want copy objects, copy keys (as array) , enumerate them this:
nsarray *keyscopy = [[self.planetdictionary allkeys] copy]; (nsstring *key in keyscopy) { if (![key isequaltostring:planet]) { nsnumber *update = [nsnumber numberwithfloat:updatedprobability]; [self.planetdictionary setvalue:update forkey:key]; } }
Comments
Post a Comment