使用Plist字典来设置应用程序设置

3

我希望能够在我的应用程序中使用plist文件进行设置。我想要一个名为“Settings”的字典来保存我的数组,例如“Debug”、“Option 1”、“Option 2”等。如何访问“Settings”字典下的“Debug”数组?

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSString *myPlistPath = [documentsDirectory stringByAppendingPathComponent:@"ProfileManager.plist"]; 
NSDictionary *plistDict = [[NSDictionary alloc] initWithContentsOfFile:myPlistPath]; 

swDebug.on = [plistDict objectForKey:@"Debug"];

.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>Current Profile</key>
<string>Sample Profile</string>
<key>Custom Profiles</key>
<array>
    <dict>
        <key>autolock</key>
        <false/>
        <key>bluetooth</key>
        <false/>
        <key>desc</key>
        <string>Example profile provided by the application</string>
        <key>edge</key>
        <false/>
        <key>phone</key>
        <false/>
        <key>push</key>
        <false/>
        <key>ringtone</key>
        <string>Example.m4r</string>
        <key>threeg</key>
        <false/>
        <key>title</key>
        <string>Example Profile</string>
        <key>vibrate</key>
        <false/>
        <key>wifi</key>
        <false/>
    </dict>
    <dict>
        <key>autolock</key>
        <false/>
        <key>bluetooth</key>
        <false/>
        <key>desc</key>
        <string>Sample profile provided by the application</string>
        <key>edge</key>
        <false/>
        <key>phone</key>
        <false/>
        <key>push</key>
        <false/>
        <key>ringtone</key>
        <string>Sample.m4r</string>
        <key>threeg</key>
        <false/>
        <key>title</key>
        <string>Sample Profile</string>
        <key>vibrate</key>
        <false/>
        <key>wifi</key>
        <false/>
    </dict>
</array>
<key>Settings</key>
<dict>
    <key>Debug</key>
    <string>ON</string>
</dict>
</dict>
</plist>
1个回答

2

在您的示例中,Debug是一个字符串,而不是数组(这与您在问题中所说的不同)。无论哪种情况,问题都在于您正在访问错误的字典键。您有:

swDebug.on = [plistDict objectForKey:@"Debug"];

您需要:

swDebug.on = [[plistDict objectForKey:@"Settings"] objectForKey:@"Debug"];

由于settings是plist字典中的一个子字典。


那么你如何回写DEBUG? - WrightsCS
你不能这样做,因为你有一个不可变的结构。如果你想要这样做,你需要创建一个NSMutableDictionary而不是NSDictionary。自己处理它也相当昂贵,因为改变任何东西都需要完全重写文件。你最好使用NSUserDefaults来处理这种情况。 - Louis Gerbarg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接