Should I use NSUserDefaults or plist to store data?

I will store a few lines (maybe 10-20). I'm not sure if I should use NSUserDefaults to save them or write them to a plist. What is considered best practice? NSUserDefaults seems like these are fewer lines of code, so it’s faster to implement.

I would like to add that these string values ​​will be added / deleted by the user.

+48
objective-c iphone cocoa-touch nsuserdefaults plist
Aug 14 '11 at 18:37
source share
9 answers

I accept an array, but it will also work with dictionaries.

Userdefaults, Core Data and Plists can be read and written, but if you use plist, you need to pay attention to what you put. See the plist section below.

Basic data I think it is too much overflow, it is just lines. It should be used when you want to save more complex objects.

NSUserDefaults

This is fairly quick and easy to do, although it should only store user settings. To write them to userdefaults:

NSArray *stringsArray = [[NSArray alloc] arrayWithObjects: string1, string2, string3, nil]; [[NSUserDefaults standardUserDefaults] setObject:stringsArray forKey:@"MyStrings"]; [[NSUserDefaults standardUserDefaults] synchronize]; 

To read data from user rights:

 NSArray *stringsArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"MyStrings"]; 

Plist

If your lines are changed, you will need to write and read plist, but you will not be able to write to your application resources.

  • So that the read / write layer first finds the document directory

     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *stringsPlistPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Strings.plist"]; 
  • Create an array (I assume the strings are string1, ...)

     NSArray *stringsArray = [[NSArray alloc] arrayWithObjects: string1, string2, string3, nil]; 
  • Write it to a file

     [stringsArray writeToFile:stringsPlistPath atomically:YES]; 

To read plist:

  • Find a document catalog

     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *stringsPlistPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Strings.plist"]; 
  • Read this:

     NSArray *stringsArray = [NSArray arrayWithContentsOfFile:stringsPlistPath]; 
+82
Aug 14 '11 at 20:13
source share

If you save 10-20 lines and are looking for not too many lines of code, the main data is definitely too much overhead. I recommend going with a plist. Not much code:

 NSURL *plistURL = [[NSBundle mainBundle] URLForResource:@"MyStrings" withExtension:@"plist"]; NSArray *stringArray = [NSArray arrayWithContentsOfURL:plistURL]; 
+7
Aug 14 '11 at 18:57
source share

iOS eventually saves all NSUserDefaults data to a NSUserDefaults file. Thus, it will not affect performance if it bothers you. I personally prefer to use NSUserDefaults for small data and plist for a relatively large data set.

Note. Never store sensitive information in NSUserDefaults , as everyone can see this data.

+7
Mar 09 '15 at 11:13
source share

NSUserDefaults will save the user preferences in a file to the Library / Preferences folder. Theoretically, it serves only to store some properties of the application / user.

A Plist file is useful for managing a single file. If you need to manage more, you should use Coredata. There is no limit to the size of the plist file. Otherwise, you should be careful with the plist file, because when you need to save or read it, the entire contents of the file will be loaded into memory.

+4
Aug. 14 '11 at 19:09
source share

It depends on what you want to keep and why. NSUserDefaults is designed to store user settings. You can try using it for other things, but you probably shouldn't.

Otherwise, if your needs are simple, the plist file is pretty simple. You can also use master data or create your own file format. In general, I use plist for simple tasks, and then move on to the main data for something more complex.

+2
Aug 14 '11 at 18:56
source share

Using plist is a good choice for storing your strings, if strings are not just user preferences that NSUserDefaults can do. As already mentioned, when using plist, you must save your plist in the Documents directory in order to write to it, because you cannot write to your own application resources. When I first found out about this, I didn’t understand where your own application bundle directory is, where the “Documents” directory is, so I thought I would post here an example code that first plist copies “Strings.plist” (this is you you already have the application in your own Bundle directory) in the Documents directory, and then write to it and read it.

 // Make a path to the plist in the Documents directory NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *stringsPlistPathIndDoc = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"Strings.plist"]; // Make a path to the plist in your app Bundle directory NSString *stringsPlistPathInBundle = [[NSBundle mainBundle] pathForResource:@"Strings" ofType:@".plist"]; NSFileManager *fileManager = [NSFileManager defaultManager]; // Check first that you haven't already copied this plist to the Documents directory if (![fileManager fileExistsAtPath:stringsPlistPathIndDoc]) { NSError *error; // Copy the plist from the Bundle directory to the Documents directory [fileManager copyItemAtPath:stringsPlistPathInBundle toPath:stringsPlistPathIndDoc error:&error]; } // Write your array out to the plist in the Documents directory NSMutableArray *stringsArray = [[NSMutableArray alloc] initWithObjects:@"string1", @"string2", @"string3", nil]; [stringsArray writeToFile:stringsPlistPathIndDoc atomically:YES]; // Later if you want to read it: stringsArray = [[NSMutableArray alloc] initWithContentsOfFile:stringsPlistPathIndDoc]; 
+2
Dec 06 '14 at 2:44
source share

NSUSerDefaults really fast to implement, but basically as your application grows you want to store more and more, I went directly for the plist files.

Basically, people want to keep a list of something, so here's my share on how to do this with NSDictionary. This does not require that you first create a plist file, it will be created the first time you save something.

xcode 7 beta, Swift 2.0

preservation

 func SaveItemFavorites(items : Array<ItemFavorite>) -> Bool { let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray let docuDir = paths.firstObject as! String let path = docuDir.stringByAppendingPathComponent(ItemFavoritesFilePath) let filemanager = NSFileManager.defaultManager() let array = NSMutableArray() for var i = 0 ; i < items.count ; i++ { let dict = NSMutableDictionary() let ItemCode = items[i].ItemCode as NSString dict.setObject(ItemCode, forKey: "ItemCode") //add any aditional.. array[i] = dict } let favoritesDictionary = NSDictionary(object: array, forKey: "favorites") //check if file exists if(!filemanager.fileExistsAtPath(path)) { let created = filemanager.createFileAtPath(path, contents: nil, attributes: nil) if(created) { let succeeded = favoritesDictionary.writeToFile(path, atomically: true) return succeeded } return false } else { let succeeded = notificationDictionary.writeToFile(path, atomically: true) return succeeded } } 

A small note from the documents:

NSDictionary.writeToFile (path: atomically :)

This method recursively checks that all contained objects are objects in the property list (instances of NSData , NSDate , NSNumber , NSString , NSArray or NSDictionary ) before writing to the file, and returns NO if all objects are not objects in the property list, since the resulting file will not a valid property list.

So, everything you set in dict.SetObject() must be one of the above types.

loading

 private let ItemFavoritesFilePath = "ItemFavorites.plist" func LoadItemFavorites() -> Array<ItemFavorite> { let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as NSArray let docuDir = paths.firstObject as! String let path = docuDir.stringByAppendingPathComponent(ItemFavoritesFilePath) let dict = NSDictionary(contentsOfFile: path) let dictitems : AnyObject? = dict?.objectForKey("favorites") var favoriteItemsList = Array<ItemFavorite>() if let arrayitems = dictitems as? NSArray { for var i = 0;i<arrayitems.count;i++ { if let itemDict = arrayitems[i] as? NSDictionary { let ItemCode = itemDict.objectForKey("ItemCode") as? String //get any additional let ItemFavorite = ItemFavorite(item: ItemCode) favoriteItemsList.append(ItemFavorite) } } } return favoriteItemsList } 
+2
Jul 13 '15 at 18:37
source share

The recommended way to save data, such as using master data. Although NSUserDefaults can be used to store more or less everything that is supposed to be used to store preferences.

+1
Aug 14 '11 at 18:40
source share

Using .plist

  • Creating a plist using Xcode

Enter plist value

 NSURL *plistURL = [[NSBundle mainBundle] URLForResource:@"settings" withExtension:@"plist"]; NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfURL:plistURL]; [dict setValue:@"value" forKey:@"key"]; [dict writeToURL:plistURL atomically:YES]; 

Read the value from plist

 NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfURL:plistURL]; NSString *myValue = [dict valueForKey:@"key"]; 
+1
Jul 06 '15 at 6:30
source share



All Articles