How can i save objects, but not overwrite in Objective C? - objective-c

Hello :)
How can i save objects, but not overwrite in Objective C,
i tried NSUserDefaults but when i add object, it will overwrite !
how can i prevent this, because i am trying to create a favorites in my app or bookmarks,
but i don't know how to save those objects i am trying to save.
This is when i am trying to save.
NSUserDefaults *favorite = [NSUserDefaults standardUserDefaults];
[favorite setObject:saveTip forKey:#"saveTipFavorite"];
[favorite synchronize];
But i overwrite every time i push add to favorite button in my app !
And i don't want it to overwrite, but make a new object and append it.
I hope you understand me :)

It is overwriting because there can only be one object per key, and you are changing it each time. What you want to do, is store an array instead of a single object, and set that as a key in your user defaults.
Initialization:
NSMutableArray *objectArray;
NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
NSArray *oldSavedArray = [currentDefaults objectForKey:#"savedArray"];
if (oldSavedArray != nil)
objectArray = [[NSMutableArray alloc] initWithArray:oldSavedArray];
else
objectArray = [[NSMutableArray alloc] init];
Notice we are converting from NSArray to NSMutableArray because the user defaults can only store the immutable (NSArray) version.
Then to add an item:
[objectArray addObject:whatever];
[currentDefaults setObject:objectArray forKey:#"savedArray"];
If this is something you will be doing a lot (tons of data), you may consider using Core Data instead, it will be faster. NSUserDefaults is not really meant for storing heavy data.

The object you save can be an array. Create an array to save the tips and make that the object given to NSUserDefaults.

NSUserDefaults is fine for simple stuff, but if you want your App to handle significant amount of data, you will want to start using CoreData.
http://developer.apple.com/library/mac/#documentation/cocoa/Conceptual/CoreData/cdProgrammingGuide.html
Not only will this solve your saving problem, it will also make it easier to manipulate your data.

Related

Problems in getting an array from NSUserDefaults

I am making a game using cocos2d-iphone and would like to make a screen with best previous scores. I have two scenes. In the MainScene I made a global variable for storing a score, that is obviously changing during the game; one mutable array and one simple array that will be a duplicate for the mutable one:
NSInteger _scoreValue;
NSMutableArray *_scoresMutable;
NSArray *_scores;
In the same class, when game ends, I add new score to the mutable array, make a static duplicate and save it in NSUserDefaults:
[_scoresMutable addObject:#(_scoreValue)];
_scores=[NSArray arrayWithArray:_scoresMutable];
[[NSUserDefaults standardUserDefaults] setObject:_scores forKey:#"gameScores"];
Then, in other class of scene with scores called bestscores(I don't know how is better, but it was easier for me to make just a new scene, because I am using SpriteBuilder) I import MainScene.h just in case and make a label.
At the moment I am trying to get all scores from NSUserDefaults, to sort it and to show second biggest value. But it always shows 0 (label is empty by default). So, how to make that's all right?
- (void)didLoadFromCCB {
NSSet *numberSet = [NSSet setWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:#"gameScores"]];
NSArray *sortedNumbers = [[numberSet allObjects] sortedArrayUsingDescriptors:#[[NSSortDescriptor sortDescriptorWithKey:#"self" ascending:NO] ]];
NSNumber *secondHighest;
if ([sortedNumbers count] > 1){
secondHighest = sortedNumbers[1];
}
[_secondBiggestLabel setString:[NSString stringWithFormat:#"%ld",(long)secondHighest]];
}
`
EDIT : synchronize didn't help. Maybe I need to write something else to get access to NSUserDefaults from another one class?
When you set the object you have to follow it with a call to synchronize. That will actually save it.
[[NSUserDefaults standardUserDefaults] synchronize];
Are you sure you've initialized that '_scoresMutable' array?
Also, if the code from the below section is ran on a separate launch than when the first section of code is ran, it's possible you're terminating the app before the defaults can write to disk. Call 'synchronize' on the NSUserDefaults instance to fix that.

arrayWithArray not resetting values

I am currently working on a tile-based-game with numbers in Xcode. In my method called checkGameOver, every tile is moved around to every combination possible, and checked if they are valid moved. However, since that method changes the mutable array called 'values',and I thought the easiest way to avoid this would be to just make a copy of 'values', store it into 'originalValues' and then restore it afterwards. However, it does seem like it actually doesn't change back. I tried using copy also. I don't understand why it doesn't work. Could it be that checkGameOver is really because of the thousands of calculations, and it isn't finished until after the values are changed back?
NSArray *originalValues = [NSMutableArray arrayWithArray:values];
[self checkGameOver];
values = [NSMutableArray arrayWithArray:originalValues];
Explanation: I have array A (values), I create a duplicate of that array, B (originalValues). I make changes on A, but the changes are reflected in B as well.
If you want to make a deep copy of an NSArray, you need to use archiving. See the following example:
NSMutableArray *values = [#[#"one", #"two"] mutableCopy];
NSData *originalValues = [NSKeyedArchiver archivedDataWithRootObject:values];
[values replaceObjectAtIndex:1 withObject:#"something"];
NSLog(#"changed: %#", values);
values = [NSKeyedUnarchiver unarchiveObjectWithData:originalValues];
NSLog(#"restored: %#", values);

Public Array? Making array accessible by multiple classes

I am trying to save lessons in a day (from text-fields) into an array so that I can save them, and later display them on a new view.
My current code:
//monLessons = Monday's lessons
NSMutableArray *monLessons;
monLessons = [NSMutableArray arrayWithObjects: self.mon1.text, self.mon2.text, self.mon3.text, self.mon4.text, self.mon5.text, self.mon6.text, nil];
Cheers!
If it is just this one NSMutableArray that you want to access from multiple classes - NSUserDefaults would be the easiest and cleanest solution.
Example
So save the NSMutableArray:
[[NSUserDefaults standardUserDefaults]setObject:YOUR ARRAY forKey:#"MondayLessons"];
Now NSUserDefaults returns a immutable copy of the a array when you ask for it - you will need to return it like this:
NSMutableArray *yourArray = [[[NSUserDefaults standardUserDefaults]objectForKey:#"MondayLessons"] mutableCopy];
This way you get an NSMutableArray back and not an NSArray
Edit 2
I forgot to add:
Before you close your application or move to a new ViewController - you need to save the data to NSUserDefaults So please call - [[NSUserDefaults standardUserDefaults]synchronize];
Anytime you want to save. If you don't call this line of code - when you ask NSUserDefaults for your Array - it will be nil. You need to do this every time you make a change to the array you're saving.

Creating a plist to access a variable and rewriting it

Is it possible to create a plist to hold one variable integer called CurrentQuestion which can be altered.
This variables value will be constantly changed by various different classes which can access the new value of the currentQuestion.
I seem to be having a problem transferring the value of variables using the prepareForSegue function and think this option may be the best option.
You should use NSUserDefaults to store this.
// setting logic
[[NSUserDefaults standardUserDefaults] setInteger:1 forKey:#"CurrentQuestion"];
[[NSUserDefaults standardUserDefaults] synchronize];
// retrieval logic
NSInteger currentQuestion = [[NSUserDefaults standardUserDefaults] integerForKey:#"CurrentQuestion"];
It will persist between application launches as well so take that into consideration.

Storing user input from text field into an NSArray

I am trying to store user input text (in this case a book title) into an array so that I can output it in a table view in another xib.
I'm getting stuck trying to store the "bookTitle.text" info into my "userinfoArray". I know it probably has a simple solution and I know how to do it in C++ but not in Objective-C. Any tips, links etc. would be great.
NSMutableArray *userinfoArray = [[NSMutableArray alloc]init];
NSString *tempString = [[NSString alloc]initWithString:[bookTitle text]];
[userinfoArray addObject:tempString];
you can then access it later with:
[userinfoArray objectAtIndex:0];
NSMutableArray is very flexible. with addObject:object you can add as many things as you want, remove them with removeObjectAtIndex:index.
more here: NSMutableArray Class Reference
alternatively if you know what size your array will have you can use a normal NSArray: NSArray Class Reference which will work similar
sebastian
Try
userinfoArray = [NSArray arrayWithObject:[bookTitle text]];
Or if you want to create a longer array with more objetcs then
userinfoArray = [NSArray arrayWithObjects:[bookTitle text], secondObject, thirdObject, nil];
If you want to add or remove objects later then you may want to use NSMutableArray instead.
If this does not answer your question, then please try to be a bit more specific about your problem.