Xco*_*der 0 iphone cocoa-touch plist nsmutablearray
我试图从一个plist得到一个数组,如答案所示,但它不起作用.有人能告诉我我错过了什么吗?
这是plist的样子......另一个奇怪的是我无法在纯文本文件中打开它?当我这样做看起来像垃圾.....但它在属性列表编辑器中看起来很好:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>count</key>
<array>
<integer>5</integer>
</array>
<key>username</key>
<array>
<string>johnsmith</string>
</array>
</dict>
</plist>
Run Code Online (Sandbox Code Playgroud)
这是我正在使用的代码.....字典是NSMUtableDictionary,accountsArray是.h文件中的NSMustableArray.
NSMutableDictionary *tempDictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:accountsFilePath];
dictionary = tempDictionary;
[tempDictionary release];
NSMutableArray *nameArray = [[NSMutableArray alloc] init];
nameArray = [dictionary objectForKey:@"username"];
accountsArray = nameArray;
[nameArray release];
Run Code Online (Sandbox Code Playgroud)
我错过了什么吗?搞砸了什么?
谢谢...
那么,有很多问题正在发生; 首先,plist可能是二进制属性列表,实际上并不是XML属性列表.这在代码方面并不重要,但应该用于解释以纯文本形式打开的问题.
其次,通过释放tempDictionary
,你也会释放dictionary
,因为它们都指向同一个对象.这应该可以解释为什么你的代码不起作用.尝试autorelease
,或简单地dictionaryWithContentsOfFile:
和完全释放发布短语.(dictionaryWithContentsOfFile:
将自动恢复其返回值.)
你也在第二个短语上重复发布错误; 赋值运算符(=
)不会在Objective-C中复制; 它分配.
编辑:使用属性表示法时后者不正确; 假设定义了属性; self.accountsArray = nameArray
会(可能)将数组复制到对象中.
Reedit:正确的代码:
dictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:accountsFilePath];
accountsArray = [dictionary objectForKey:@"username"];
Run Code Online (Sandbox Code Playgroud)