iPhone NSMutableDictionary setObject forKey 在 initWithContentsOfFile 之后

发布于 2024-10-09 18:54:25 字数 590 浏览 2 评论 0原文

所以这是我的函数

+ (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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

向日葵 2024-10-16 18:54:25

首先,您宁愿尊重 ObjC 的命名约定,以便更容易理解...例如,方法名称以小写字母开头,最好在每个参数的冒号之前放置一个描述性名称,例如方法名称那: AddAddress:: 不太好...

现在,关于从文件加载字典,问题是如果文件无法加载(不存在,格式错误) ,...),返回的对象将为 nil,纠正这个问题的最简单方法是输入:

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

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];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文