On Mon, Dec 29, 2008 at 4:16 AM, Steve Cronin <email@hidden>
wrote:
Kyle;
Thanks for that pointer! Based on the documentation you cited I've
now got
the reading of NSUserDefaults functioning!
In the hopes that it might be useful to someone else, I include
these 'Cocoa
friendly' methods.
I grant that there are some improvements which could be made, I
include them
here in the spirit of helpfulness to the community....
// myBundleID is a static string defined elsewhere
//retrieves the full user defaults dictionary
- (NSDictionary *) prefDictionary {
CFStringRef appBundleID = (CFStringRef)myBundleID;
return (NSDictionary *)CFPreferencesCopyMultiple(NULL,
appBundleID,
kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
}
Note that this returns a retained object and thus violates Cocoa
memory management guidelines. This is OK if the code calling it knows
this and releases it, but since it probably doesn't then this will
cause a leak every time it's called. And it's much better to fix this
up to autorelease the dictionary when returning it than to patch up
the caller to do so.
//retrieves the string Value of a key [full implementation of all
the
CFPropertyList types is left as an exercise for the reader)
- (NSString *) prefStringValueforKey:(NSString *)preferenceKey {
CFStringRef appBundleID = (CFStringRef)myBundleID;
return
(NSString*)CFPreferencesCopyValue((CFStringRef)preferenceKey,
appBundleID, kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
}
Rather than a full implementation of all the types, why not just a
single method which returns id?
Note that you get no real type safety here because the cast to
NSString* will succeed even if the actual value is a number,
dictionary, array, or date.
//sets the value for a key
- (void) setPrefValue:(id)preferenceValue forKey:(NSString
*)preferenceKey {
CFStringRef appBundleID = (CFStringRef)myBundleID;
CFPreferencesSetValue((CFStringRef)preferenceKey,
(CFPropertyListRef)preferenceValue, appBundleID,
kCFPreferencesCurrentUser, kCFPreferencesAnyHost);
CFPreferencesSynchronize(appBundleID,
kCFPreferencesCurrentUser,
kCFPreferencesAnyHost);
}
No comment here!
Just a little comment here (from the Preferences Best Practices)
- Only synchronize when absolutely necessary
You may have a valid reason to sync at each write, but have a look at
the "Synchronizing Preferences Across Process Boundaries" section for
more infos.