I'm creating a very simple bookmarks menu for my app. I just need to save 3 strings for each object.
I was thinking of using core data but I don't want this to be connected with my core database for various reasons. Therefore what other easy options do I have? NSUserDefaults or .plist?
I just need to save the 3 strings for each object then load them into a table view to be viewed.
I'd recommend NSUserDefaults - is certainly easier. I tend to only use plist files for static data that I want to be editable as the developer, but from the application want it to be read-only (such as coordinates for objects on an embedded map image).
From your description, you would probably want to store an NSArray containing NSDictionary.
// Get the user defaults object
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
// Load your bookmarks (editable array)
NSMutableArray *bookmarks = [[NSMutableArray alloc]init];
NSArray *bookmarksLoaded = [userDefaults arrayForKey:#"bookmarks"];
if (bookmarksLoaded != nil) {
[bookmarks initWithArray:bookmarksLoaded];
} else {
[bookmarks init];
}
// Add a bookmark
NSMutableDictionary *bookmark = [NSMutableDictionary new];
[bookmark setValue:#"value" forKey:#"name"];
[bookmark setValue:#"value" forKey:#"description"];
[bookmark setValue:#"value" forKey:#"code"];
[bookmarks addObject:bookmark];
// Save your (updated) bookmarks
[userDefaults setObject:bookmarks forKey:#"bookmarks"];
[userDefaults synchronize];
// Memory cleanup
[bookmarks release];
Related
I have an issue persisting data in local storage for an NSMutableArray containing a list of NSStrings.
I have a save method and a get method both appear to work when the app is running. However, once I close the app and restart the items in the array are gone.
NSMutableArray*ImageTags;
Get Data
-(NSMutableArray*)GetDataNSMutableArray:(NSString*)ItemName
{
NSMutableArray *GetData = [[NSMutableArray alloc] init];
NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
NSData *dataRepresentingSavedArray = [currentDefaults objectForKey:ItemName];
if (dataRepresentingSavedArray != nil)
{
NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingSavedArray];
if (oldSavedArray != nil)
GetData = [[NSMutableArray alloc] initWithArray:oldSavedArray];
else
GetData = [[NSMutableArray alloc] init];
}
return GetData;
}
Save Data
-(void)SaveDataNSMutableArray:(NSString*)ItemName:(NSMutableArray*)Data
{
[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:Data] forKey:ItemName];
}
How items are added
[ImageTags addObject:Control.titleLabel.text]
How array is saved
[super SaveDataNSMutableArray:CVC_ImageURL:ImageTags];
How array is retrieved
ImageTags = [super GetDataNSMutableArray:CVC_ImageURL];
NSUserDefaults always return immutable instances.
Unrelated:
(Conventions says that methodNames should always begin with a small letter).
[[NSUserDefaults standardUserDefaults] synchronize]
To dump all the contents from NSUserDefaults onto persistent store
Your can not store mutable array to user defaults. Store the immutable copy and retrieve that and convert to mutable ones to access during the next launch.
You can do synchronization while saving:
-(void)SaveDataNSMutableArray:(NSString*)ItemName:(NSMutableArray*)Data
{
[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:Data] forKey:ItemName];
[[NSUserDefaults standardUserDefaults] synchronize] //add this code of a line.
}
I have created application that record sound and display that sound file in tableview. In that application when sound is recorded than it's filepath will store in a array , which array i use to populate my tableview. But my problem is that when i close the application then my array will be empty , and i lost my recorded file.
So now how can i get my recorded file when i open my app second time. I am storing sound file in document directory.
Store array in NSUserDefaults. Retrive and Store the array in NSUserDefaults .. see the example of NSUserDefaults
In AppDelegate.h file just declare variable...
NSUserDefaults *userDefaults;
NSMutableArray *yourArray;
after...
In AppDelegate.m Fille in applicationDidFinishLonching: Method
userDefaults = [NSUserDefaults standardUserDefaults];
NSData *dataRepresentingtblArrayForSearch = [userDefaults objectForKey:#"yourArray"];
if (dataRepresentingtblArrayForSearch != nil) {
NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingtblArrayForSearch];
if (oldSavedArray != nil)
yourArray = [[NSMutableArray alloc] initWithArray:oldSavedArray];
else
yourArray = [[NSMutableArray alloc] init];
} else {
yourArray = [[NSMutableArray alloc] init];
}
[yourArray retain];
after that when you want to insert Data in this UserDefaults Use Bellow Code...
[appDelegate.yourArray addObject:yourDataString];///set your value or anything which you want to store here...
NSData *data=[NSKeyedArchiver archivedDataWithRootObject:appDelegate.yourArray];
[appDelegate.userDefaults setObject:data forKey:#"yourArray"];
[appDelegate.userDefaults synchronize];
i hope this help you...
In my application, I am using a login form to enter into the application, also using NSUserDefaults to store user preferences, for example:
[storeData setObject:self.loginField.text forKey:#"USEREMAIL"];
[storeData setObject:self.PasswordField.text forKey:#"PASSWORD"];
Like I stored, if a new user logs in the NSUserDefaults stored value will be changed. But I want both preferences (ex:new userid and old userid as well as password). So please explain how to store multiple values for same key?
One way to solve this would be to store a NSDictionary with UserIDs as keys and the passwords as values.
Another option is to use Keychain as it specifically designed for this kind of thing and is also more secure.
Create a Global NSMutableArray and add above details in NSDictionary Objects and Store all Objects in array.This way you will have all user objects.You can get it whenever you want.
first of all create global array with AppDelegate class, for example..
userDefaults = [NSUserDefaults standardUserDefaults];
NSData *dataRepresentingtblArrayForSearch = [userDefaults objectForKey:#"arrScheduleDates"];
if (dataRepresentingtblArrayForSearch != nil) {
NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingtblArrayForSearch];
if (oldSavedArray != nil)
arrScheduleDates = [[NSMutableArray alloc] initWithArray:oldSavedArray];
else
arrScheduleDates = [[NSMutableArray alloc] init];
} else {
arrScheduleDates = [[NSMutableArray alloc] init];
}
[arrScheduleDates retain];
after that when you want to store the new record then get all record from arrScheduleDates array and after that add the new record and after that store like whole array like above..
i hope you understand and its helpful for you...
:)
The absolute easiest way to meet your requirements is to use the user's email address (assuming they're all unique) as the storage key for your dictionary, and the password as the value.
If you need to store more than the password, then the value of the key would be another dictionary with keys and values for the user.
An example of the simple case would look similar to :
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSDictionary *storedUsers = [userDefaults objectForKey:#"userData"];
if (nil == storedUsers) storedUsers = [NSDictionary dictionary];
NSMutableDictionary *mutableStoredUsers = [NSMutableDictionary dictionaryWithDictionary:storedUsers];
NSString *userPassword = [self.PasswordField.text copy]; //add autorelease if you aren't using ARC
NSString *userEmail = [self.loginField.text copy]; //add autorelease if you aren't using ARC
if (nil != userEmail)
{
[mutableStoredUsers setObject:userPassword forKey:userEmail];
}
[userDefaults setObject:[NSDictionary dictionaryWithDictionary:mutableStoredUsers] forKey:#"userData"];
[userDefaults synchronize];
first download and import files of given link
https://github.com/ldandersen/scifihifi-iphone/tree/master/security
then where u want to store user preferences write this code
[SFHFKeychainUtils storeUsername:loginField.text andPassword:PasswordField.text forServiceName:#"dhaya" updateExisting:YES error:&error];
where u want password write this code
NSString *password = [SFHFKeychainUtils getPasswordForUsername:loginField.text andServiceName:#"dhaya" error:&error];
NSLog(#"passwordpassword %#",password);
this will working great....
i need your help,i Am stuck in a simple problem,i done a lot of googling but did not get solution.
I want to store Top 5 scores and with names, i done score by NSUserDefaults but don't know how to store it with names.Please help me.I really need your help.
THANKS...
you can save into user defaults as
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
NSDictionary* dict = [[NSDictionary alloc] initWithObjectsAndKeys:#"jonny",#"name",#"100",#"score", nil];
NSArray* arr = [[NSArray alloc] initWithObjects:dict, nil];
[defaults setObject:arr forKey:#"list"];
[defaults synchronize];
[dict release];
[arr release];
and read the values as
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
NSArray* arr = [defaults objectForKey:#"list"];
NSLog(#"%#",[arr objectAtIndex:0]);
this works fine for you, it will be a array of dictionaries.
I recommend you familiarize yourself with basic Objective-C collection classes. You can use an NSDictionary to store objects, and those objects can be other objects. You can use this dictionary in combination with NSUserDefaults to store only what you want to store, after having some logic in your app that analyzes your collection class.
Pick up a good book on Objective-C and study sets, arrays and dictionaries.
I'm new to Core Data and I need some help on my project.
I'm developing iPhone app that get JSON (Restaurants info) from server and shows the location on the map and table view, and stores favorite restaurants by pressing "add favorite" button.
For now, I'm just using NSDictionary and its functions to display data on the table and annotations and having favoriteRestaurant entity to store favorite restaurant data.
However, I would like to convert the NSDictionary object into Core Data object (Restaurant), and add "BOOL isFavorite" attribute to it and then delete favoriteRestaurant entity.
Make function that saves the restaurant object that passed and changes its "isFavorite" state, which is triggered by "add Favorite" button.
The favorite table shows only the restaurants that has been saved and isFavorite = YES.
I would like to know if this is right approach to accomplish what I want.
Thank you in advance!
Hi, thank you for fast responses. I forgot to say that I also want to implement MKAnnotation to that class so each annotation pin on the map belongs to unique restaurant object. If I want to do this, should I have another favorite class or Core Data entity, or just save it in the Restaurant table and make isFavorite = YES? Thank you, again!
If you're only concerned about saving the favorites then id go with plist serialization. I do the same thing in multiple apps. Normally I create a Helper class like below.
#import "Favorites.h"
#import "NSArray+Locations.h"
#implementation Favorites
+(void)addFavorite:(Location *)location{
NSMutableArray *remove = [NSMutableArray array];
[location.data enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSLog(#"%#,%#, %#",key,obj,[obj class]);
if([obj isKindOfClass:[NSNull class]])
[remove addObject:key];
}];
[location.data removeObjectsForKeys:remove];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary * favorites = [NSMutableDictionary dictionaryWithDictionary:[defaults objectForKey:FAVORITES]];
if(!favorites)
favorites = [NSMutableDictionary dictionaryWithCapacity:1];
[favorites setObject:location.data forKey:[location getID]];
[defaults setObject:favorites forKey:FAVORITES];
[defaults synchronize];
}
+(void)removeFavorite:(Location *)location{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary * favorites = [NSMutableDictionary dictionaryWithDictionary:[defaults objectForKey:FAVORITES]];
[favorites removeObjectForKey:[location getID]];
[defaults setObject:favorites forKey:FAVORITES];
[defaults synchronize];
}
+(NSArray *)getFavorites{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary * favorites = [defaults objectForKey:FAVORITES];
return [NSArray arrayWithLocations:[favorites allValues]];
}
+(BOOL)isFavorited:(Location *)location{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary * favorites = [defaults objectForKey:FAVORITES];
for(NSString *key in [favorites allKeys])
if([[location getID] isEqualToString:key])
return YES;
return NO;
}
#end
In this case the Location object is just a wrapper around a dictionary to make accessing the fields simpler.
If you want to save all of your data and not just favorites then I would go with core data otherwise a very large plist could give you memory headaches.
I like your approach. In my opinion Core Data is the way to go.
If you get lots of JSON records (say, dozens or hundreds of restaurants) with maybe even more data fields in the future, you could run into memory problems when using an array of NSDictionarys. Remember, a serialized plist can only be retrieved entirely, so if it gets large you will have to keep all the data in memory.
Also, you will very like have a much better performance from the start.
Your BOOL attribute (in Core Data that would be a NSNumber) should work fine for your purpose.