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?
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.
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!");