-2

I use NSUserDefaults as following

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    BOOL downloaded = [prefs boolForKey:@"downloaded"];


    if (! downloaded ) {


        [self MoveAndBuild ];

        [prefs setBool:YES forKey:@"downloaded"];   


        //////////// Write to the file to prevent re import at the next time .





    }

my question is can NSUserDefaults carry object of class , I mean I have a class and want to save object of it to be act as default is applicable , another question can NSUserDefaults store nsstring

any suggestion please

Jaffer Wilson
  • 7,029
  • 10
  • 62
  • 139
AMH
  • 6,363
  • 27
  • 84
  • 135
  • 6
    Have you looked at the [documentation for NSUserDefaults](http://tinyurl.com/5rgrlbj)? I ask because the third paragraph of the Overview section answers your question and points you to more information. – Caleb Jun 14 '11 at 06:55
  • the problem was in the encoding part see the answer , don't judge – AMH Jun 14 '11 at 07:52

3 Answers3

2

We use NSUserDefaults to store objects, and an object can be of any type i:e NSString, NSArray, Class Objects etc. For Storing you can use:

[defaults setObject:anyObject forkey:@"objectKey"];
  • Developer "and an object can be of any type" part of your answer is incorrect. please edit your answer. – Tatvamasi Jun 30 '11 at 00:12
1

Your custom class object needs to implement the NSCoding protocol.

Check the below SO post.

How to store custom objects in NSUserDefaults

Community
  • 1
  • 1
Jhaliya - Praveen Sharma
  • 31,697
  • 9
  • 72
  • 76
0

NSUserDefaults can store (and only store) plist-objects. please see http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/UserDefaults/UserDefaults.html for programming NSUserdefaults.

Tatvamasi
  • 2,537
  • 19
  • 14
  • Ah I see: the objects a property list can store. Anyway: this answer is wrong. Any NSCoding compliant object can be stored, as [Jhaliya](http://stackoverflow.com/questions/6340031/nsuserdefaults-question/6340092#6340092) pointed out. – vikingosegundo Jun 29 '11 at 19:00
  • @vikingosegundo "The NSUserDefaults class only supports the storage of objects that can be serialized to property lists. This limitation would seem to exclude many kinds of objects, such as NSColor and NSFont objects, from the user default system. But if objects conform to the NSCoding protocol they can be archived to NSData objects, which are property list–compatible objects" excerpt from the documentation. There is no direct way to store non plist objects, even though NSCoding complaint. You need to archive it to get NSData, which is a plist compatible object. – Tatvamasi Jun 30 '11 at 00:09
  • But the OP is about NSUserDefaults. and not plist – vikingosegundo Jun 30 '11 at 08:42
  • @AMH can you please let me know if I understod your question properly ? finding it difficult to understand @vikingosegundo perspective :) – Tatvamasi Jun 30 '11 at 11:07