开发者

iPhone NSMutableDictionary setObject forKey after initWithContentsOfFile

开发者 https://www.devze.com 2023-02-02 04:22 出处:网络
so here\'s my function + (void) AddAddress:(NSString*)ip:(NSString*)mac { NSMutableDictionary* currentAddresses = [[NSMutableDictionary alloc] initWithContentsOfFile:[self filePath:ADDRESSES_FILE]];

so here's my function

+ (void) AddAddress:(NSString*)ip:(NSString*)mac {
    NSMutableDictionary* currentAddresses = [[NSMutableDictionary alloc] initWithContentsOfFile:[self filePath:ADDRESSES_FILE]];
    [currentAddresses setObject:mac forKey:ip];
    [Configuration Write:currentAddresses];
    [currentAddresses release];
}

[self filePath:ADDRESSES_FILE] returns a string containing the 开发者_如何学编程full path of a file (ADDRESSES_FILE) located in the Documents. The file may not exist, in this case I want to just write an object to the dictionary and then write it down

the problem is that when i do setObject forKey it doesn't add anything to the dict (if i just do alloc init to the dict, it works fine, but i want to read the records from the file, if there are any, and replace/add a record by using the AddAddress function)


First thing first, you'd rather respect naming convention of ObjC to be more easily understood... For instance, method names start with a small case and it's better to put a descriptive name before the colons for each arguments, a method name like that: AddAddress:: isn't really good...

Now, about loading a dictionary from a file, the thing is that if the file can't be loaded (doesn't exist, wrong format,...), the returned object will be nil, the simplest way to correct that is to put:

if(currentAddresses == nil) currentAddresses = [[NSMutableDictionary alloc] init];
0

精彩评论

暂无评论...
验证码 换一张
取 消