Storing object on iOS - best solution?

半城伤御伤魂 提交于 2019-12-01 22:59:28

问题


I'm building an app for a blog where a user can save their favorite posts.

When they do, I want to store my object which contains: the post's URL, title and image URL.

Should I go for UserDefaults (formerly NSUserDefaults) or start with Core Data right away?


回答1:


Should I go for User Defaults or start with Core Data right away?

There are more possibilities here: you can also use plain files or plists, or use sqlite without Core Data. The answer depends on the number of items that you plan to store:

  • If you plan to store 1 to 20 items, user defaults would work fine
  • If you plan to store 20 to 200 items, plain files or plists would work
  • If you plan to store 200+ items, go for Core Data or sqlite, depending on your level of comfort with one of these technologies.



回答2:


Since favorites for articles generally wont be 100K item then I would use NSDictionary for an item and store them into a NSMutableArray and then save them to a file. It is simple to use and you can also export the favorites to a file or even iCloud to share between devices.

NSMutableDictionary *item = [[ NSMutableDictionary alloc]init];
[item setObject:@"www.google.com" forKey:@"url"];
[item setObject:@"Google" forKey:@"title"];

//Add each item to the Favourites array
//You should declare this outside of the "addToFavourites" function.
NSMutableArray *Favourites = [[NSMutableArray alloc]initWithObjects: nil];
[Favourites addObject:item];

//Save the Favourites NSMutableArray to the file.
if([Favourites writeToFile:path atomically:NO]) 
   NSLog(@"Favourites are saved!");


来源:https://stackoverflow.com/questions/14107516/storing-object-on-ios-best-solution

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!