iPhone: NSMutableDictionary key - iphone

I was trying to use a CLLocation object as a key for a dictionary... but it doesnt seem to work. Works well if I use a string. Is this not possible?
[dict setObject:tmp forKey:tmpLocation]; // objectForKey always returns null on same location

I ended up passing a string lat/long combo which served my purpose.

Related

How To remove a key value from Plist in ios?

I wanted to delete the key value in the Plist. I found answers like to delete the value assigned to it and another is to load a new plist but i need to delete a key value
(assuming this is programming-related)
You can load it into an NSDictionary, remove the key/value pair, then write it back:
NSString *pathToPlist = #"/Users/H2CO3/my.plist";
NSMutableDictionary *plist = [NSMutableDictionary dictionaryWithCOntentsOfFile:pathToPlist];
[plist removeObjectForKey:#"MyKeyIWannaDelete"];
[plist writeToFile:pathToPlist atomically:YES];
As of now this is not possible via coding. If you have these kind of scenario's, go with the database. So that, you can delete, what ever the row you want?
PlistDict is the Dictionary that is loaded in to the plist .By using following code we can remove the key value from the plist.
[plistDict removeObjectForKey:#"Key"];
Dictionary must be a Mutable one(NSMutableDictionary).

Adding multiple values as a single entry into an NSMutableArray and retrieving it

I retrieve 6 values(say name, age, sex, address, id, tag) from a web service. All are string variables. I concatenate these strings and add it to an NSMutableArray. I pass this array to another class, where I need each of these strings separately. That is I need to be able to retrieve these values from the array separately. How can I do this.
Do I need to add tags like "Name", "Age" etc along with the values to make the retrieval easier. Whats the appropriate way to do it.
Edit: i concatenate it into a single string. How should I be adding my values to the collection, so that I can retrieve the elements easily.
IMO, the most appropriate way of doing what you are trying to do is using an NSMutableDictionary, that allows you to access individual elements based on their key.
Example:
loadedBuffers = [[NSMutableDictionary alloc] initWithCapacity:CD_BUFFERS_START];
[loadedBuffers setObject:bufferId forKey:filePath];
...
[loadedBuffers objectForKey:filePath]
You do no strictly need using a dictionary, but it will make your life so much easier.
In your case (if I understand it correctly), I would do:
NSMutableArray* result = [NSArray arrayWithCapacity:kNUM_OF_ROWS];
NSString *name, *age, *sex....;
<for each set of strings from the web service>
<retrieve strings>
NSMutableDictionary dict = [NSMutableDictionary dictionaryWithCapacity:kNUM_OF_FIELDS];
[dict setObject:name forKey:#"name"];
...
[dict setObject:address forKey:#"address"];
[result addObject:dict];
<end_for>
return result;
By doing like this, you will be able to access sequentially each set of strings; then access each string individually.
In short, instead of encoding your set of strings by concatenating them into another string, you would expand them in a dictionary to make retrieval easier.
I would agree that the best practise here would be to use a dictionary or custom object. That way each string gets stored with its companions (e.g. you have one person's data all together) and you don't have to deal with the messy method you already have implemented. It sounds like you might want to save data, so here's a snippet to help you. If that's not what you're after, let me know and I'll modify my response to help!
Say you have a custom object class Person, where you create and manage data objects to save to disk via the app delegate. You'd do something like:
Person *newPerson = [[Person alloc] init];
[newPerson setName:#"John"];
[newPerson setAge:#"25"];
[newPerson setSex:#"M"];
[yourAppDelegate.newPersonArray insertObject:newPerson atIndex:[mainDelegate.newPersonArray count]];

How to get object for key from NSDictionary?

In dictionary named dict the key value pair is:
"alba\U2019s window" = "A model in westindies.";
And to send objectForKey: I am getting the string like "alba's window". When I send like following:
[dict objectForKey:alba's window];
I am not getting anything, it is showing null.
For starters, you might want to make that an actual string, like so:
[dict objectForKey:#"alba's window"];
Note also that \U2019 is not '; but ’, which is a different character entirely.
And more generally, sticking to [a-zA-Z0-9]+ for dictionary keys is probably a good idea, unless you are inserting and retrieving programmatically using the exact same string as a key.
Since iOS6 onwards, a convenient method for setting and accessing the object for a key from an NSDictionary is:
//Setting the object in NSMutableDictionary
dictionary[#"someKey"] = #"someString";
//Accessing the object
NSString *str = dictionary[#"someKey"];
Make sure your dict isn't null; sending a message to a null object will silently fail and return null.
Another way to check your key/values is to simply NSLog(#"%#",dict); and this will show you the contents of the dictionary. Note that this output only shows quotes around values when the value contains a space.
Also, make sure you're using the same pairs of strings as the key - it looks like you're using "alba\U2019s window" in addition to "alba's window".

How to get some values from json saved in nsstring?

My WS returns simple json like this:
{
"thumbnail_url": "http://something.com/photos/003/582/test-tiny.jpg?1321956139",
"success": true,
"photo_url": "http://something.com/photos/003/582/test-medium.jpg?1321956139",
"big_photo_url": "http://something.com/photos/003/582/test-big.jpg?1321956139"
}
I get this in NSData from NSURLConnection. I know how to make NSString from NSData. I would like to get value for "photo_url" key.
How can it do this?
You have to use SBJSON framework to get value of photo_url.
in SBJSON framework have one method that return NSMutableDictionary For String.
You can use like this [string JSONValue] that will return NSMutableDictionary.
After that use will be get value from this code [dict valueForKey:#"photo_url"]
Thanks,
MinuMaster
Use TouchJSON or SBJson parser to parse this.
For iOS 5 only you can use the built in NSJSONSerialization class.
If you need to support iOS4 then JSONKit is a good solution.
You can then query your results like a normal dictionary.

Objective C - Problem with objectForKey

Okay, I'm trying to write a high score function for my app.
My problem is that when no high score has been saved yet, my program crashes.
If I save it with:
[[NSUserDefaults standardUserDefaults] setObject:#"[given string]" forKey:#"firstName"];
first, it works fine. However, if I start up the program for the first time and try to view the high scores with the following code:
first = [[NSString alloc] initWithString:[[NSUserDefaults standardUserDefaults] objectForKey:#"firstName"]];
bad things happen.
Basically, is there away to see if nothing yet exist under firstName? Is there a way to initialize without erasing any name that might already be present?
Thanks.
The NSString documentation for initWithString: says
Parameters
aString
The string from which to copy characters. This value must not be nil.
The documentation for objectForKey: says
Return Value
The object associated with the
specified key, or nil if the key was
not found.
The problem seems to be that there is a nil returned when you try to retrieve firstName that doesn't exist yet and try to create a NSString with it as input.
The NSUserDefaults instance method registerDefaults: is meant for exactly this purpose: You can set default values for your preferences that will be overridden by any other value set for the same preference key. Just make sure to call it early enough that it will run before any code that needs to access your preferences.
You could load "first" like this:
first = [[[NSUserDefaults standardUserDefaults] objectForKey:#"firstName"] retain];
if (!first) {
// set default or do something else if there wasn't a value saved
first = #"N/A";
}