NSUserDefaults display date and data in the tableView - iphone

In the FirstViewController of my survey app I have NSMutableArray that contains data (strings). I've also created date varibale. Here's code
NSDateFormatter *dateformater=[[NSDateFormatter alloc] init];
[dateformater setDateFormat:#"EEEE,dd MMMM yyyy HH:mm a"];
NSDate *today=[NSDate date];
NSString *currentDate=[dateformater stringFromDate:today];
Now I want with the help of NSUserDefaults save data from the array and also save date variable when the survey has been taken and display it in the SecondViewController's tableview (first user can see date of the survey and then by tapping the date - data from array).
I know how NSUSerDefaults work but I don't know how to put array by date variable to be shown in the SecondViewController. Can anyone help me on that?

In AppDelegate.h file just declare variable...
NSUserDefaults *userDefaults;
NSMutableArray *arrDate;
after...
In AppDelegate.m Fille in applicationDidFinishLonching: Method
userDefaults = [NSUserDefaults standardUserDefaults];
NSData *dataRepresentingtblArrayForSearch = [userDefaults objectForKey:#"arrDate"];
if (dataRepresentingtblArrayForSearch != nil) {
NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingtblArrayForSearch];
if (oldSavedArray != nil)
arrDate = [[NSMutableArray alloc] initWithArray:oldSavedArray];
else
arrDate = [[NSMutableArray alloc] init];
} else {
arrDate = [[NSMutableArray alloc] init];
}
[arrDate retain];
after that when you want to insert,update or delete Data from this UserDefaults Use Bellow Code...
for Delete record from array
[appDelegate.arrDate removeObjectAtIndex:Index];/// give the integer value instead of Index
and this is for add record in array..
[appDelegate.arrDate addObject:currentDate];///add value or add date here
after in final save this modification in array just archive like bellow..
NSData *data=[NSKeyedArchiver archivedDataWithRootObject:appDelegate.arrDate];
[appDelegate.userDefaults setObject:data forKey:#"arrDate"];
[appDelegate.userDefaults synchronize];

Create a NSDictionary with the date and data object:
NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:#"%#",currentDate], #"date", #"yourData", #"data", nil];
Then put it in the NSUserDefault using:
[NSUserDefaults standardUserDefaults] setObject:yourDictionary forKey:#"item1"];
This will store a single data to NSUserDefault.
You can retrieve the object by using:
NSDictionary * dictionary = [[NSUserDefaults standardUserDefaults] dictionaryForKey:#"item1"];
Now you will get the date using [dictionary objectForKey:#"date"]; and data using : [dictionary objectForKey:#"data"];

Related

Unable to retrieve NSMutableArray from NSUserDefaults

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.
}

How to retrive data from document directory when application start?

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...

NSDictionary Inside An NSDictionary

I have the following code:
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *golferIconsu = [userDefaults objectForKey:#"golferIconsFirstScene"];
NSMutableDictionary *golferIconsSceneOne = [[NSMutableDictionary alloc]initWithDictionary:golferIconsu];
NSMutableDictionary *savedScoreCards;
NSMutableDictionary *currentScoreCard;
[currentScoreCard setObject:golferIconsSceneOne forKey:#"golferIconsFirstScene"];
NSMutableDictionary *GI = [currentScoreCard objectForKey:#"golferIconsFirstScene"];
[savedScoreCards setObject:currentScoreCard forKey:#"1"];
NSLog([golferIconsSceneOne objectForKey:#"30101"]);
NSLog([GI objectForKey:#"30101"]);
At the end all that is printed out in my log is the first NSLog call, not the second one. For example:
NSLog([golferIconsSceneOne objectForKey:#"30101"]);
This prints out a string that I stored in that dictionary.
This one:
NSLog([GI objectForKey:#"30101"]);
Doesn't print out anything at all.
How can I get the NSDictionary GI to have the exact same properties as golferIconsSceneOne, but I need to do this using the currentScoreCardDictionary, which contains golferIconsSceneOne?
Initialise your dictionary before setting object in it.
NSMutableDictionary *savedScoreCards = [[NSMutableDictionary alloc] init];
NSMutableDictionary *currentScoreCard = [[NSMutableDictionary alloc] init];
Do like this intialize one and set it into other
NSMutableDictionary *savedScoreCards = [[NSMutableDictionary alloc] init];
NSMutableDictionary *currentScoreCard = [[NSMutableDictionary dictionaryWithDictionary:savedScoreCards];

Objective C - UserDefaults Over Writing

I can't seem to re edit this object in my ios User Defaults. Here is my code...
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:nil forKey:#"savedScoreCards2"];
Before I did this I set the key savedScoreCards to a huge 3-d dictionary, and now when I try to over write it or even set the key to nil that huge 3-d dictionary that I set up a while ago is still there. I can't seem to over write/ replace it will nothing (nil), or another huge 3-d dictionary. Any ideas?
UPDATE:
+ (void)saveCurrentScoreCard
{
//save score card
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *savedScoreCards = [[NSMutableDictionary alloc] init];
[userDefaults setObject:nil forKey:#"savedScoreCards2"];//reset at beginning
NSMutableArray *golferOneScoresu = [userDefaults arrayForKey:#"golferOneScoresArray"];
NSMutableArray *golferTwoScoresu = [userDefaults arrayForKey:#"golferTwoScoresArray"];
NSMutableDictionary *golferIconsu = [userDefaults objectForKey:#"golferIconsFirstScene"];
NSMutableArray *golferThreeScoresu = [userDefaults arrayForKey:#"golferThreeScoresArray"];
NSMutableArray *golferFourScoresu = [userDefaults arrayForKey:#"golferFourScoresArray"];
NSMutableDictionary *golferIcons2u = [userDefaults objectForKey:#"golferIcons"];
NSMutableArray *golferNamesu = [userDefaults objectForKey:#"golferNames"];
NSMutableArray *golferNames = [[NSMutableArray alloc] initWithArray:golferNamesu copyItems:YES];
NSMutableDictionary *golferIconsSceneOne = [[NSMutableDictionary alloc]initWithDictionary:golferIconsu];
NSMutableDictionary *golferIcons = [[NSMutableDictionary alloc]initWithDictionary:golferIcons2u];
NSMutableArray *golferFourScores = [[NSMutableArray alloc] initWithArray:golferFourScoresu copyItems:YES];
NSMutableArray *golferThreeScores = [[NSMutableArray alloc] initWithArray:golferThreeScoresu copyItems:YES];
NSMutableArray *golferOneScores = [[NSMutableArray alloc] initWithArray:golferOneScoresu copyItems:YES];
NSMutableArray *golferTwoScores = [[NSMutableArray alloc] initWithArray:golferTwoScoresu copyItems:YES];
NSMutableDictionary *currentScoreCard = [[NSMutableDictionary alloc] init];
[currentScoreCard setObject:golferNames forKey:#"golferNames"];
[currentScoreCard setObject:golferIconsSceneOne forKey:#"golferIconsFirstScene"];
[currentScoreCard setObject:golferIcons forKey:#"golferIcons"];
[currentScoreCard setObject:golferOneScores forKey:#"golferOneScoresArray"];
[currentScoreCard setObject:golferTwoScores forKey:#"golferTwoScoresArray"];
[currentScoreCard setObject:golferThreeScores forKey:#"golferThreeScoresArray"];
[currentScoreCard setObject:golferFourScores forKey:#"golferFourScoresArray"];
[savedScoreCards setObject:currentScoreCard forKey:#"1"];
NSLog([golferIconsSceneOne objectForKey:#"30101"]);
[userDefaults setObject:savedScoreCards forKey:#"savedScoreCards2"];
[userDefaults synchronize];
NSLog(#"SAVED SCORE CARD");
}
Use [userDefaults removeObjectForKey:#"savedScoreCards2"] if you're just trying to remove a stored value.
Also call [userDefaults synchronize]; to "flush" your changes immediately. I think the [userDefaults synchronize] is probably what you're missing.
NSUserDefaults do not save automatically when you make a change to them. Try adding this line below the ones you've posted above:
[userDefaults synchronize];
This should save any changes you've made.
As a side note, I'm not sure you can save 'nil' into NSUserDefaults; at its core I believe it's a dictionary, in which nil values cannot be set. So you might try setting an empty object, instead.
Hope this helps, let me know if you need any more information!

Sort items in a UITableView by date

So in my app, I have a UITableView, and in the navigation controller there is a button to add a new item. This than takes you to an add an item screen and when you finish, i use a custom delegate to pass the information from the detail viewController to the main tableViewController. Now that I have the info from delegate, I take the 3 pieces of info and put them in an NSArray in my main Array. Now my question is, how can I sort the detail items by date. I have tried (unsuccessfully) 3 times now and I can't seem to figure it out. The arrays and dictionarys get confusing because they are nested. Any help is greatly appreciated.
The Delegate Method in the tableViewController class:
-(void)finishedAddingFoodItemFromDetail:(NSDate *)date whatWasEaten:(NSString *)whatFood whichMeal:(NSString *)meal{
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MMMM d, yyyy"];
NSString *dateString = [[NSMutableString alloc] init];
dateString = [dateFormatter stringFromDate:date];
if (!self.theArray) {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:#"theArray"]) {
self.theArray = [defaults objectForKey:#"theArray"];
}
else{
self.theArray = [[NSMutableArray alloc] init];
}
}
[self.theArray addObject:[NSArray arrayWithObjects:dateString, meal, whatFood, nil]];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:self.theArray forKey:#"theArray"];
[self.tableView reloadData];
[self dismissModalViewControllerAnimated:YES];
}
This is the file higharchy I was thinking of, but I can't seem to implement it.
/* file higharchy
* - theBigDict //large dictionary holding everything
* - MutableArray by day stored as objects of theBigDict
* - Array of the meals info:
* - Meal type
* - Food
*/
There are several methods on NSMutableArray you can call to sort its contents:
– sortUsingDescriptors:
– sortUsingComparator:
– sortWithOptions:usingComparator:
– sortUsingFunction:context:
– sortUsingSelector:
Since you have an array of complex objects, you will need to write your own function or comparator and call the appropriate sortUsingXxx: method. Do this before you store the array back into NSUserDefaults and before calling reloadData: on your table.
Does this help?
EDIT: Your custom function or comparator will have to pull out the date from the two array elements being compared (passed into your function) and return the appropriate comparison results, e.g. NSOrderedAscending, etc.