Able to add objects to NSMutableDictionary, but trying to access objects gives 'unrecognized selector' error

StackOverflow https://stackoverflow.com/questions/23080067

سؤال

I'm using ARC, and I'm almost certain this is a memory related issue.

I have several classes: DiningHall, Meal, and Station. DiningHalls store various meals using a mutable dictionary, and each meal stores various stations using another mutable dictionary. When I try to access a station from the meal's stationList property, I get the following error:

Below is the code I tested to debug: before I add a new station to the dictionary, I tried listing the dictionary's existing contents, giving me the following error:

'NSInvalidArgumentException', reason: '-[__NSCFString name]: unrecognized selector sent to instance 

Inside DiningHall class:

- (void) addStation:(Station*)s toMeal:(NSString*) mealType {

     Meal *m = [self.mealList objectForKey:mealType];
    NSArray* a = [m.stationList allKeys];
    for (Station* s in a)
        NSLog(@"%@", s.name); //line generating error
    [m addStation:s];

}

Inside Meal class:

- (void)addStation:(Station *)station {

    [self.stationList setObject:station forKey:station.name];
   //also tried  [self.stationList setValue:station forKey:station.name];
}

In init of meal class:

self.stationList = [[NSMutableDictionary alloc] init];

The reason I think this is a problem with the dictionary is that when I replaced the stationList dictionary with a mutable array, (and adjusted the test code appropriately), it did not crash.

هل كانت مفيدة؟

المحلول

You error is in this line of code:

NSArray* a = [m.stationList allKeys];
for (Station* s in a)
     NSLog(@"%@", s.name); //line generating error

Because the array a contain the key and the value of the dictionary. And since you set the key of the dicionary to station.name array a only contains strings and not atations.

Try:

NSArray* a = [m.stationList allValues];
for (Station* s in a)
     NSLog(@"%@", s.name); //line generating error

نصائح أخرى

You are setting the station.name as key:

[self.stationList setObject:station forKey:station.name];

And then you try to access the station object when iterating over all keys:

for (Station* s in a)
    NSLog(@"%@", s.name); 

But the keys will only give the station names. You want

NSLog(@"%@", [self.stationList objectForKey:s]);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top