How can I use NSDictionary's methods to add objects and keys? - iphone

I want to make an NSDictionary that has the following values where symbol & id are my keys.
I want to map "AAPL" to symbol
I want to map 100 to id.
"AAPL":symbol
"100":id
"GOOG":symbol
"101":id
"YHOO":symbol
"102":id
How can I create a dictionary of these values with
dictionaryWithObjectsAndKeys

Which one is key, which one is value? Assuming you want map symbol to id, then
NSDictionary *myDict = [NSDictionary dictionaryWithObjectsAndKeys:
#"100", #"AAPL", // 100 is object, AAPL is key
#"101", #"GOOG",
#"102", #"YHOO",
// etc...
nil];
If the IDs are numbers, use
NSDictionary *myDict = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt: 100], #"AAPL",
// etc...
nil];
If, OTOH, you want to map ids to symbols, then reverse the entries:
NSDictionary *myDict = [NSDictionary dictionaryWithObjectsAndKeys:
#"AAPL", #"100",
#"GOOG", #"101"
// etc...
nil];

The data you describe would most likely be represented by an array of dictionaries, since the keys would be repeated for each entry.
NSArray *array = [NSArray arrayWithObjects:[NSDictionary dictionaryWithObjectsAndKeys:#"APPL", #"symbol", #"100", #"id", nil], [NSDictionary dictionaryWithObjectsAndKeys:#"GOOG", #"symbol", #"101", #"id", nil], [NSDictionary dictionaryWithObjectsAndKeys:#"YHOO", #"symbol", #"103", #"id", nil], nil];

Assuming you want to use the ids as the keys and the symbols as the values, this should work:
NSDictionary *stocks = [NSDictionary dictionaryWithObjectsAndKeys:#"AAPL", #"100", #"GOOG", #"101", #"YHOO", #"102", nil];

Related

Retrive values from NSDictionary

I am trying to retrieve the values from my NSDictionary however I am running into errors, I was wondering if someone might be able to help me with my solution.
I have 18 values, not all are shown here that I am checking, when the correct key is reached I would like to take the value in the NSDictionary and pass it into one of my NSString variables.
Below is an example of what I am trying to do however like I say I am having several issues
for (id key in searchData) {
if ([[searchData objectForKey:key] isEqualToString:#"Code"]) {
codeSeries = [searchData objectForKey:key];
}
else if ([[searchData objectForKey:key] isEqualToString:#"ID"]) {
IDSeries = [searchData objectForKey:key];
}
// ...
However, when I try to log out any of the values, they all return Null. I have checked the dictionary before hand and the values are all most definitely in there, so I am thinking there is something wrong with my code above.
Any help would be greatly appreciated.
Update
This is how I create the NSDictionary
//start of mymethod...
NSDictionary *sendSeriesDictionary = [[NSDictionary alloc] init];
// Keys for sendSeriesDictionary
NSArray *keys = [NSArray arrayWithObjects:#"Code", #"ID", nil];
// Objects for keys that are for sendSeriesDictionary
NSArray *objects = [NSArray arrayWithObjects: [NSNull null], IdString, nil];
// Add keys and objects to NSDictionary
sendSeriesDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
[engineRequests SeriesSearch:sendSeriesDictionary]; // this is where I send the NSDictionary over to where I want to read it.
//end of mymethod
You've got several problems. First, you mix up keys and values (like Tom said). Second, you have a possible memory leak where you create the dictionary, or at least a unnecessary instantiation.
Try this for creating the dictionary:
// Keys for sendSeriesDictionary
NSArray *keys = [NSArray arrayWithObjects:#"Code", #"ID", nil];
// Objects for keys that are for sendSeriesDictionary
NSArray *objects = [NSArray arrayWithObjects: [NSNull null], IdString, nil];
// Add keys and objects to NSDictionary
NSDictionary *sendSeriesDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
Retrieving the values can be done like this:
codeSeries = [searchData objectForKey:#"Code"];
IDSeries = [searchData objectForKey:#"ID"];
In your first loop you looped through all the keys, got their values and then compared those to the key again. Which makes no sense.
Are you mixing keys and values ?
Maybe you just want codeSeries = [searchData objectForKey:#"Code"]; ?

AFNetworking - Build NSDictionary parameters

I'm trying to build my NSDictionnary to send to a request using the AFNetworking framework, but it seems that I'm quite confused about how to do it properly.
Here's what the server is expecting :
{
"limit":10,
"filters":
[
{"field":"owner","operator":"EQUAL","value":"ownerId","type":"integer"},
{"field":"date","operator":"GE","value":"30 Jun 2010 00:00:00","type":"date"},
],
"order":[{"field":"date","order":"ASC"}],
"page":0
}
What I'm trying to do (I don't really know if it's the right way to do it tbh), is to build a NSDictionary like the following :
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:
#"10", #"chunkSize",
[NSDictionary dictionaryWithObjectsAndKeys:
[NSDictionary dictionaryWithObjectsAndKeys:#"owner", #"field", #"EQUAL", #"operator", #"ownerId", #"value", #"integer", #"type", nil],
[NSDictionary dictionaryWithObjectsAndKeys:#"date", #"field", #"GE", #"operator", #"30 Jun 2010 00:00:00", #"value", #"date", #"type", nil],
nil], #"filters",
[NSDictionary dictionaryWithObjectsAndKeys:
[NSDictionary dictionaryWithObjectsAndKeys:#"date", #"field", #"ASC", #"order", nil],
nil], #"order",
#"0", #"page",
nil];
But I have the following error when the view is loading :
*** Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '+[NSDictionary dictionaryWithObjectsAndKeys:]: second object of each pair must be non-nil
I know I screw up building the parameters properly, but I can't manage to do it after several tries. Could anyone help ? Moreover, I don't really know the differences that I must implement here with the [] and the {}. I read that {} was for a dictionary and [] for an array, but I don't really see how to translate it in my case.
Your mistake is that the value for the dictionary starting on line 3 needs to be wrapped in an array.
At least until Objective-C array and hash literals go mainstream, my preferred method for creating complex dictionaries is to build them from an NSMutableDictionary. In your case:
NSMutableDictionary *mutableParameters = [NSMutableDictionary dictionary];
[mutableParameters setValue:#"10" forKey:#"limit"];
// ...
NSMutableArray *mutableFilters = [NSMutableArray array];
NSMutableDictionary *mutableOwnerFilterDictionary = [NSMutableDictionary dictionary];
[mutableOwnerFilterDictionary setValue:#"owner" forKey:#"field"];
// ...
[mutableFilters addObject:mutableOwnerFilterDictionary];
[mutableParameters setValue:mutableFilters forKey:#"filters"];
// ...
Also, be sure you're sending that over as JSON by setting AFJSONParameterEncoding to your AFHTTPClient.
The brackets [] signify an array, while the braces {} signify an object (dictionary in this context). To produce the structure you require:
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:
#"10", #"chunkSize",
[NSArray arrayWithObjects:
[NSDictionary dictionaryWithObjectsAndKeys:#"owner", #"field", #"EQUAL", #"operator", #"ownerId", #"value", #"integer", #"type", nil],
[NSDictionary dictionaryWithObjectsAndKeys:#"date", #"field", #"GE", #"operator", #"30 Jun 2010 00:00:00", #"value", #"date", #"type", nil],
nil], #"filters",
[NSArray arrayWithObjects:
[NSDictionary dictionaryWithObjectsAndKeys:#"date", #"field", #"ASC", #"order", nil],
nil], #"order",
#"0", #"page",
nil];

iOS - deleting all entries containing a key on all NSDictionaries stored inside a main NSDictionary

I have a main NSMutableDictionary that contains a collection of others NSMutableDictionary.
The thing goes like this:
NSMutableDictionary *subDict1 = [NSMutableDictionary dictionaryWithObjectsAndKeys:
obj1, #"name",
obj2, #"color",
nil];
NSMutableDictionary *subDict2 = [NSMutableDictionary dictionaryWithObjectsAndKeys:
obj3, #"name",
obj4, #"color",
obj5, #"address",
obj6, #"phone",
obj7, #"color",
obj8, #"parent",
nil];
NSMutableDictionary *subDict3 = [NSMutableDictionary dictionaryWithObjectsAndKeys:
obj0, #"name",
obj9, #"parent",
objA, #"site",
objB, #"surname",
objC, #"label",
nil];
These sub dictionaries may have different number of entries and the keys may vary. Some may have keys with the same name.
They are stored in a main dictionary like this:
NSMutableDictionary *mainDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:
subDict1, #"1",
subDict3, #"3",
subDict2, #"2",
nil];
I want at one shot, remove all entries in all sub dictionaries that have a specific key.
I know I can iterate thru the dictionaries and sub dictionaries, but I also know that Dictionaries have smart ways to do that using predicates and other stuff, but I am not seeing how. I am trying to find that because the method this will run is a little bit tricky and have to do it as fast as possible and I am not sure if normal iteration with loops or whatever will be fast enough...
Any clues? thanks.
Here's a recursive method that doesn't care how many levels deep the target key is. (haven't tried it) ...
- (void)removeKey:(NSString *)keyToRemove fromDictionary:(NSMutableDictionary *)dictionary {
NSArray *keys = [dictionary allKeys];
if ([keys containsObject:keyToRemove]) {
[dictionary removeObjectForKey:keyToRemove];
} else {
for (NSString *key in keys) {
id value = [dictionary valueForKey:key];
if ([value isKindOfClass:[NSMutableDictionary self]]) {
[self removeKey:keyToRemove fromDictionary:(NSMutableDictionary *)value];
}
}
}
}
You'll need to just iterate through all the subdirectories and remove the appropriate key-value pairs manually. You shouldn't worry if it's fast enough at this point. Rather, create a working implementation and test/measure it. If it's too slow, then you can profile it and come up with ways to improve performance. Premature optimization is a bad thing.
NSArray* keys = [NSArray arrayWithObjects:#"name", #"address", nil];
[dics removeObjectsForKeys:keys]; //Or sub dics

printing values of keys in NSDictionary

What I am having so far right now is
NSArray *keys = [NSArray arrayWithObjects:#"firstName",#"lastName",#"phoneNumber",#"email",#"password",nil];
NSArray *objects = [NSArray arrayWithObjects:#"nil",#"nil",#"nil",#"nil",#"abc",nil];
dictionary = [NSDictionary dictionaryWithObject:objects forKey:keys];
NSLog(#"pass is %#",[keys objectAtIndex:4]);
NSLog(#"value of pass is%#",[dictionary objectForKey:#"password"]);
However, What I got from the debugger is
pass is password
value of pass is (null)
Can anyone explain why the value is null.It should be abc,shouldn't it.
The following line would have given a warning:
dictionary = [NSDictionary dictionaryWithObject:objects forKey:keys];
It should read:
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
Change this line you are missing s
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
you can do it in the fallowing way also...
NSMutableDictionary *dictionary=[NSMutableDictionary dictionaryWithObjectsAndKeys:#"nil",#"firstName",#"nil",#"lastName",#"nil",#"phoneNumber",#"nil",#"email",#"abc",#"password", nil];
NSLog(#"value of pass is%#",[dictionary objectForKey:#"password"]);

Create an NSDictionary of NSDictionaries

Believe it or not, I have searched the internet before asking this question. Unbelievably, I have yet to find a nice clear example of how to create an NSDictionary of NSDictionaries.
Here is my code so far, but it prints null. Any ideas?
// Here I am creating the dictionaries in the code until I start getting them from the server ;)
NSArray *keys = [NSArray arrayWithObjects:#"mission", #"target", #"distance",#"status", nil];
NSArray *objectsA = [NSArray arrayWithObjects:#"tiger", #"bill", #"5.4km", #"unknown", nil];
NSDictionary *tiger = [NSDictionary dictionaryWithObjects:objectsA
forKeys:keys];
NSArray *objectsB = [NSArray arrayWithObjects:#"bull", #"roger", #"10.1km", #"you are dead", nil];
NSDictionary *bull = [NSDictionary dictionaryWithObjects:objectsB
forKeys:keys];
NSArray *objectsC = [NSArray arrayWithObjects:#"peacock", #"geoff", #"1.4km", #"target liquidated", nil];
NSDictionary *peacock = [NSDictionary dictionaryWithObjects:objectsC
forKeys:keys];
// activeMissions = [NSArray arrayWithObjects:tiger, bull, peacock, nil];
[activeMissions setObject:tiger forKey:#"tiger"];
[activeMissions setObject:bull forKey:#"bull"];
[activeMissions setObject:peacock forKey:#"peacock"];
NSLog(#"active Missions %#", activeMissions);
You are not intializing activeMissions, that is why the NSLog statement is printing null (sending a message to a nil object in ObjC return nil).
Put this before assigning to activeMissions:
NSMutableDictionary *activeMissions = [NSMutableDictionary dictionaryWithCapacity:3];
Otherwise, if you prefer having a non mutable NSDictionary, you could do:
NSDictionary *activeMissions = [NSDictionary dictionaryWithObjects: [NSArray arrayWithObjects:tiger, bull, peacock, nil]
forKeys: [NSArray arrayWithObjects:#tiger, #"bull", #"peacock", nil]];
(Keep in mind that this is autoreleased, you'll have to retain somehow).