some_id
some_id

Reputation: 29896

Saving an array to NSUserDefaults

How is an array saved to NSUserDefaults?

I have the following code which tries to store an array of NSURLs

NSArray *temp = [[NSArray alloc] initWithArray:[mySingleton sharedMySingleton].sharedURLS];
NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
[defs setObject:temp forKey:@"URLs"];

but I get a warning

-[NSUserDefaults setObject:forKey:]: Attempt to insert non-property value

What is the correct way to store this or collection of NSURLS?

Upvotes: 4

Views: 7191

Answers (3)

Manish Saini
Manish Saini

Reputation: 67

  if you want save Object Like Array ,So you use Archived Class

    NSArray *temp = [[NSArray alloc] initWithArray:[mySingleton sharedMySingleton].sharedURLS];
    [[NSUserDefaults standardUserDefaults]setObject:[NSKeyedArchiver archivedDataWithRootObject:temp] forKey:@"URLs"];

you also need coder and decoder method for this.  
    This is Working Fine For Me.

Upvotes: 0

Anomie
Anomie

Reputation: 94804

You can't directly store an NSURL in NSUserDefaults, only NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary; also, any NSArray or NSDictionary may only contain objects of these types. You'll have to convert the NSURLs into one of these types, most likely by using absoluteString to convert them into NSStrings.

Upvotes: 10

element119
element119

Reputation: 7625

The problem resides with [mySingleton sharedMySingleton].sharedURLS. NSURls can't be stored in NSUserDefaults, at least in the NSURL class, as they aren't property list objects (explanation below). I would recommend converting the URLs to NSStrings and then placing them in NSUserDefaults, like so:

NSString *urlString = [url absoluteString];

There's a similar problem another user had here ( NSUserDefaults won't save NSDictionary), where the issue was that the objects that the programmer put into the NSDictionary (in this case, NSArray), weren't property list objects. Basically, property lists objects are things like NSData, NSString, NSNumber, NSDate, NSArray or NSDictionary, the required format for saving to NSUserDefaults.

Upvotes: 0

Related Questions