views:

332

answers:

1

I want to be able to use a plist for settings Im implementing in my app. I want a dictionary "Settings" to hold my arrays, such as "Debug", "Option 1", Option 2", etc. How would I access "Debug"array under the "Settings" dictionary?

This is what my code looks like:

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"];

Heres how the plist looks:

<?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"&gt;
<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  A: 

In your example Debug is a string, not an array (which is what you seem to say it is in the question). In either event, the issue is that you are accessing the key in the wrong dict. You have:

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

You would need:

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

Since settings is a dictionary within the dictionary plist.

Louis Gerbarg
so how do you write back to DEBUG?
AWright4911
You can't, you have an immutable structure. If you want to do that you need to create NSMutableDictionary instead of an NSDictionary. It is also pretty expensive to handle yourself because changing anything requires completely rewriting the file. You would probably be better served using `NSUserDefaults` for this kind of thing anyway.
Louis Gerbarg