哪一个是初始化NSMutableDictionary的正确方法。请有人在这里纠正我

时间:2012-02-13 15:09:41

标签: ios ios4 ios5

我正在尝试在我的班级中创建一个NSMutableDictionary。我已经在stackoverflow中阅读了很多帖子来理解其中的差异。但现在我完全糊涂了。所以任何人都纠正我,哪一个是在我的班级初始化NSMutableDictionary的正确方法。我必须在我的应用程序的许多方面访问这个dictiionary。所以建议我使用变量初始化的好方法...

/// .h file
@interface ActiveFeeds : NSObject {

}
@property (nonatomic, copy) NSMutableDictionary *invDictionary;
@property (nonatomic, retain) NSString *filePath;
@end

@implementation ActiveFeeds

@synthesize filePath;
@synthesize invDictionary;

- (id)init{

    self = [super init];
    if (self != nil){
        NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:self.filePath];
        self.invDictionary = [dictionary mutableCopy];
         dictionary release]; 
    }
    return self;
}

/* And use self.invDictionary all in the application */
- (void)setObjectAtKey:(NSMutableDictionary *)objectDic atKey:(NSString *)setKey{
    [self.invDictionary setObject:objectDic forKey:setKey];
}

- (void)dealloc {
    [self.invDictionary release];
    [self.filePath release];
    [super dealloc];
}

@end

或者喜欢这个......

@interface ActiveFeeds : NSObject {
    NSMutableDictionary *invDictionary;
    NSString *filePath;
}
@end


@implementation ActiveFeeds

- (id)init{

    self = [super init];
    if (self != nil){
            NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
            invDictionary = [dictionary mutableCopy];
            [dictionary release];
        }    
    }
    return self;
}

/* And use invDictionary all in the application */
- (void)setObjectAtKey:(NSMutableDictionary *)objectDic atKey:(NSString *)setKey{
    [invDictionary setObject:objectDic forKey:setKey];
}

- (void)dealloc {
    [invDictionary release];
    [filePath release];
    [super dealloc];
}

@end

请任何人帮助我获得使用变量的正确方法....

1 个答案:

答案 0 :(得分:2)

- (id)initWithFilePath:(NSString *)path{

    self = [super init];
    if (self != nil){
       self.filePath = path;
       self.invDictionary = [NSMutableDictionary dictionaryWithContentsOfFile:path]; 
    }
    return self;
}

- (void)dealloc {
    [invDictionary release];
    [filePath release];
    [super dealloc];
}