How i can Store top 5 Scores With names in cocos2d iphone - iphone

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.

Related

Retrieval of NSArray from NSUserDefaults returns empty array

I am experiencing strange behaviour with NSUserDefaults. I am initially storing an array to the user defaults in my AppDelegate.m:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSArray *weekdayIDs = [defaults objectForKey:#"weekdayIDs"];
if (weekdayIDs == nil) {
weekdayIDs = [NSArray arrayWithObjects:#"su", #"mo", #"tu", #"we", #"th", #"fr", #"sa", nil];
[defaults setObject:weekdayIDs forKey:#"weekdayIDs"];
}
[defaults synchronize];
Now in a different view controller ContentViewController.m, I want to retrieve the array:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSArray *weekdayIDs = [defaults objectForKey:#"weekdayIDs"];
But I just get an array without objects, although its count == 7. I also used arrayForKey: but with the same result. I added a screenshot from my breakpoint.
I am regularly using NSUserDefaults, but currently I am bit stuck on this. It's probably a stupid mistake, anyone care to help?
Thank you so much!
-- Update:
I also figured it might be a problem with the init of the NSArray in the first place, but even replacing its objects with manually created NSString *dwid_su = [NSString stringWithString:#"su"]; didn't work.
Your code works perfectly.
Just, print the description of you array and you will see what you want.
Right click on weekdayIDs variable and select Print Description of weekdayIDs
or use through lldb debugger console po weekdayIDs
or NSLog(#"%#", weekdayIDs);
Here the results.

Array within a NSDictionary: how to save to the NSUserDefaults

I would like to save Array/NSDictionary to NSUserDefaults but anything I try is just not working. Here is my code so please if you know how to do this, help me.
NSArray *oneArray = [NSArray arrayWithObjects:#"Radio One",nil];
NSDictionary *one = [NSDictionary dictionaryWithObject:oneArray forKey:#"Stations"];
NSArray *oneLinkArray = [NSArray arrayWithObjects:#"http://mobile.com:28000/",nil];
NSDictionary *oneLink = [NSDictionary dictionaryWithObject:oneLinkArray forKey:#"Stations"];
[data addObject:one];
[link addObject:oneLink];
The reason I need this is to put this station into favorites. So my thinking is to save these info in to NSUserDefaults and retrieve in favorites table.
Thanks and please any suggestion is welcomed and appreciated.
You can use something like this when you store everything into a dictionary
[[NSUserDefaults standardUserDefaults] setObject:link forKey:#"dictionary1"];
Or you can put everything into an array and store it like this
[[NSUserDefaults standardUserDefaults] setObject:data forKey:#"array1"];
You can access it again by using
NSDictionary * myDictionary = [[NSUserDefaults standardUserDefaults] dictionaryForKey:#"dictionary1"];
Typically adding an object into NSUserDefaults goes like this:
NSMutableDictionary *dictionaryToAdd = [[NSMutableDictionary alloc] init];
[dictionaryToAdd setObject:#"xyz" forKey:#"myKey"];
NSUserDefaults *myDefaults = [NSUserDefaults standardUserDefaults];
[myDefaults setObject:dictionaryToAdd forKey:#"someKey"];
[myDefaults synchronize];
A few things on your code above though - you're adding stuff into 'data' and 'link' but I don't see those in your code, so I'm assuming those arrays exist somewhere.
To sum it up - declare an NSUserDefaults object, set objects into it like an NSDictionary, and then synchronize it to save data.
Additional code as requested:
//You have an array named arrayToAdd that has already been created
NSUserDefaults *myDefaults = [NSUserDefaults standardUserDefaults];
[myDefaults setObject:arrayToAdd forKey:#"SomeKeyThatYouMakeUp"];
[myDefaults synchronize];
//You want to get the array out of NSUserDefaults
NSArray *mySavedArray;
NSUserDefaults *myDefaults = [NSUserDefaults standardUserDefaults];
mySavedArray = [myDefaults objectForKey:#"SomeKeyThatYouMakeUp"];

How To Save Data For Bookmarks?

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];

JSON and Core Data:Should I convert JSON into Core Data?

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.

Pre-populating a NSUserDefaults array with Zero Value values

I need to pre-populate and save an array in NSUserDefaults so that downstream methods can read and write to ten values stored there. I've constructed this workable solution, but is there a better way of doing this?
Any insight is appreciated!
lq
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *myArray = [[NSMutableArray alloc] init];
// Set the array with ten Zero Value placeholders
for (NSUInteger i = 0; i < 10; ++i) {
[myArray addObject:[NSNumber numberWithInt:0]];
}
[userDefaults setObject:myArray forKey:#"someKeyName"];
[myArray release];
Later methods call this array like this:
- (void)doSomethingUseful {
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *someUsefulArray = [[NSMutableArray alloc] initWithArray:[userDefaults objectForKey:#"someKeyName"]];
// read some values, write some values: int someInt = [someUsefulArray objectAtIndex:3]; // etc.
// store array values back to NSUserDefaults . . .
// IS THERE A WAY TO READ AND WRITE DIRECTLY TO INDEX 3 of the NSUserDefaults array instead???
[someUsefulArray release]
}
I've actually done the same thing in a shipping application. Sure, it doesn't feel elegant, but it does the job.
The only more elegant, and more convoluted, solution would be to use a data-driven approach:
Have a .plist file containing what you consider to be your default settings.
If the program detects that the user defaults is empty, it will load this default plist, and commit it to NSUserDefaults.
Using this method your code is not responsible for building the objects. However, if you are trying to accomplish a schema-upgrade, you're going to need to go back to the code.