Saving an array in NSUserDefaults

How is an array stored in NSUserDefaults?

I have the following code that is trying to save an NSURL array

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 a non-property value

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

+4
source share
3 answers

You cannot directly store NSURL in NSUserDefaults , only NSData , NSString , NSNumber , NSDate , NSArray or NSDictionary ; also any NSArray or NSDictionary can contain only objects of these types. You will need to convert the NSURL to one of these types, most likely using absoluteString to convert them to NSStrings.

+10
source

The problem is related to [mySingleton sharedMySingleton].sharedURLS . NSURls cannot be stored in NSUserDefaults, at least in the NSURL class, because they are not objects in the property list (explanation below). I would recommend converting the URLs to NSStrings and then putting them in NSUserDefaults, for example:

NSString *urlString = [url absoluteString];

There is a similar problem with another user ( NSUserDefaults will not save NSDictionary ), where the problem was that the objects that the programmer places in the NSDictionary (in this case, NSArray) were not property list objects. Basically, property list objects are things like NSData, NSString, NSNumber, NSDate, NSArray or NSDictionary, the format you need to save to NSUserDefaults.

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

Source: https://habr.com/ru/post/1341484/


All Articles