NSUserDefaults Declares Class

Does anybody have a working NSUserDefaults declares class that they’d like to share?

@Michel Bujardet posted a link to one a few months back in this thread https://forum.xojo.com/18185-folderitem-ios but it seems to have some issues.

You need the Foundation Module from my iOSKit on Github but this should do it once you set the Super to Foundation.NSObject. It should have basically everything except for NSURL support since I haven’t ported/implemented that class yet. NSUserDefaults will be part of iOSKit v1.1 :slight_smile:

Thanks Jason. I seem to be missing a definition for NSData?

declare function dataForKey_ lib FoundationLib selector "dataForKey:" (obj_id as ptr, defaultName as CFStringRef) as ptr Return new NSData(dataForKey_(self, defaultName))

Correct, I haven’t implemented NSData yet either so it doesn’t include that (yet). Sorry :(. That would be the correct declare - although since there is no NSData class I would recommend that you leave everything in pointers. The NSUserDefaults class will auto convert to a pointer using with operator_convert so you can use it directly as the “obj_id” parameter of that declare. Obviously you will need setData:forKey: as well when saving an NSData object:

declare sub setData_ lib FoundationLib selector "setData:forKey:" (obj_id as ptr, value as ptr, defaultName as CFStringRef) setData_(self, value, defaultName)

Thanks Jason. I don’t have a need to save anything of type NSData yet - just boolean, integer and text values at this time for user preferences - so I’ve just removed the reference to NSData for now.

Thank you so much. :slight_smile:

OK dumb question. I can successfully use the SetIntegerForKey and SetBoolForKey methods, but how do I save a text value using SetObjectForKey? It expects a value of type NSObject.

Use an NSString with SetObjectForKey. You can retrieve it with StringForKey.

Thank you.