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
CularBytes Jul 13 '15 at 18:37 2015-07-13 18:37
source share