ObjC:在循环中构造可变字典

时间:2012-08-09 22:05:11

标签: objective-c nsmutabledictionary

我觉得我已经阅读了很多(简单)的例子,这些例子完全符合我的要求。我似乎无法让这个工作。我需要第二眼看看我的代码,我周围没有任何人,所以请原谅我,如果这看起来非常简单......代码编译没有问题。谢谢!

@implementation Engine
- (id) initWithInventory: (NSString *) path {
    if (self = [super init]) {
        NSString *contents = [NSString stringWithContentsOfFile:@"ingredientList.csv" encoding:NSASCIIStringEncoding error:nil];

        NSLog(@"%@",contents); // This yields the contents of the file appropriately

        NSArray *lines = [contents componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
        NSRange ingredientRange = {0,96}; // This is done because I want to omit the last element of the array... the 97th is an empty string caused by the end of file newline character.  I know it's bad coding...

        NSEnumerator *enumerator = [[lines subarrayWithRange:ingredientRange] objectEnumerator];
        NSString *curString;
        NSArray *ingredientElements;
        NSRange activeEffectRange = {1,4}; // Element 0 will be the key, elements 1-4 are the array to be stored.

        while (curString = [enumerator nextObject]) {
            ingredientElements = [curString componentsSeparatedByString:@","];
            Ingredient *theIngredient = [[Ingredient alloc] initWithName:[ingredientElements objectAtIndex:0] andActiveEffects:[ingredientElements subarrayWithRange:activeEffectRange]];
            NSLog(@"%@",[theIngredient ingredientName]);
            NSLog(@"%@",[theIngredient activeEffects]); //These both print out correctly.

            NSString *theName = [theIngredient ingredientName];
            [allIngredients setObject:theIngredient forKey:theName];
            NSLog(@"%@",[allIngredients objectForKey:[theIngredient ingredientName]]); // ***This yields (null)***
        }
    }
    return self;
}

编辑:我应该补充一点,allIngredients是正在启动的类的实例变量,因此它被正确定义为NSMutableDictionary

@interface Engine : NSObject {
    NSMutableDictionary *allIngredients;
}
- (id) initWithInventory: (NSString *) path;
@end

1 个答案:

答案 0 :(得分:3)

你在哪里创建allIngredients?你已经声明了它,但在使用之前你还没有分配它。

allIngredients = [[NSMutableDictionary alloc] init]