开发者

Saving an array to NSUserDefaults

开发者 https://www.devze.com 2023-02-13 12:25 出处:网络
How is an array saved to NSUserDefaults? I have the following code which tries to store an array of NSURLs

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 standardUserDe开发者_Python百科faults];
[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?


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.


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.


  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.
0

精彩评论

暂无评论...
验证码 换一张
取 消