iPhone NSMutableDictionary setObject forKey 在 initWithContentsOfFile 之后
所以这是我的函数
+ (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] 返回一个字符串,其中包含位于文档中的文件(ADDRESSES_FILE)的完整路径。该文件可能不存在,在这种情况下,我只想将一个对象写入字典,然后将其写下来,
问题是当我执行 setObject forKey 时,它不会向字典中添加任何内容(如果我只是将 alloc init 分配给字典,它工作正常,但我想从文件中读取记录(如果有的话),并使用 AddAddress 函数替换/添加记录)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,您宁愿尊重 ObjC 的命名约定,以便更容易理解...例如,方法名称以小写字母开头,最好在每个参数的冒号之前放置一个描述性名称,例如方法名称那:
AddAddress::
不太好...现在,关于从文件加载字典,问题是如果文件无法加载(不存在,格式错误) ,...),返回的对象将为 nil,纠正这个问题的最简单方法是输入:
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: