0

我觉得我已经阅读了许多(简单)示例,这些示例完全符合我的要求。我似乎无法让它发挥作用。我需要重新审视我的代码,而且我周围没有任何人,所以如果这看起来很简单,请原谅我......代码编译没有问题。谢谢!

@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
4

1 回答 1

3

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

allIngredients = [[NSMutableDictionary alloc] init]
于 2012-08-09T22:13:36.037 回答