how to add arrays in dictionary based on particular key - iphone

I am making an app. where i want to add vendor name and it's device name..
I am using a dictionary where vendor name is key and device name are values..
Here is my code
[appDelegate.arrOfDevice addObject:txtDeviceName.text];
[appDelegate.dictOfDetails setObject:appDelegate.arrOfDevice forKey:txtVendorName.text ];
Here arrOfDevice is an array(declared in appdelegate) which is having all devices which are added..
I want to add devices based on particular keys...
I know, i am doing something wrong,
I am pushing the array as values in dictionary so it will store all the device names for each key.. but please help me...So that i could store device names based on particular key...
If u are not able to understand please fell free to get clarification of my question...

If you are adding key for the first time then you need to do this as shown below
if(flag==1) {
NSMutableArray *tmpArr=[[NSMutableArray alloc]init];
[tmpArr addObject:txtDeviceName.text];
[appDelegate.dictOfDetails setObject:tmpArr forKey:[txtVendorName.text uppercaseString]];
}
and if the key is present you just need to create a reference for an array and add object to the dictionary
else if(flag==0) {
NSMutableArray *arrDevice=[appDelegate.dictOfDetails objectForKey:[txtVendorName.text uppercaseString]];
[arrDevice addObject:txtDeviceName.text] ;
}

NSDictionary *dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:#"Nit",[NSNumber numberWithInt:3],nil]
forKeys:[NSArray arrayWithObjects:#"Name",#"num",nil]];
>>Edited
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:
#"value1", #"key1", #"value2", #"key2", nil];
also seem +dictionaryWithObjects:forKeys:
Hope, this will help you...

Related

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

Setting value for nsmutabledictionary in multi levels

I am trying to set a key for UserName as with respect to this code:
{
"CustomerAccount":{
"UserName":"String content"
};
I am trying to set the username here, does anyone know how can I set a name in dictionary with levels?
My code is as:
[mutabledictionary setObject:self.uitextfield.text forKey:UserName];
however this sets the username below to CustomerAccount not insider CustomerAccount.
Any help here would be appreciated.
Thanks.
If the two level mutable dictionary already exists (its not clear from your question) you need to send your setObject:forKey message to the second level dictionary, like so:
[[mutabledictionary objectForKey:#"CustomerAccount"] setObject:self.uitextfield.text forKey:UserName];
You can just add a sub-dictionary, like this:
NSDictionary *userAccount = [NSDictionary dictionaryWithObject:#"String Content" forKey:#"UserName"];
NSMutableArray *accounts = [NSMutableArray arrayWithObject:userAccount];
// do something with accounts
NSLog(#"%#", accounts);
Just create create array of CustomerAccount and use in NSDictionary. Use
[NSDictionary dictionaryWithObjects:objects forKeys:keys];

How to read all NSDictionary objects for a key to an array

I have a dictionary "playerDict" that reads data from a plist where there is names (myKey) with nine associated objects to each key.
I am trying to read all objects for a specific key (myKeys) into an NSMutableArray (theObjects). I have read the class reference and search internet but cannot figure our this, probably very simple, problem.
Among all other test i have done I have tried the following but that returns the key into theObjects and not the objects.
theObjects = [playerDict objectForKey:myKeys];
Anyone that could give a hint?
Here is the code that created the dict, i stripped it:
NSArray *objs = [NSArray arrayWithObjects:[NSNumber numberWithBool:playerObject.diffHard],[NSNumber numberWithBool:playerObject.diffMedium],
[NSNumber numberWithBool:playerObject.diffEasy],[NSNumber numberWithBool:playerObject.currentGame],
[NSNumber numberWithInt:playerObject.currentGameQuestion],[NSNumber numberWithInt:playerObject.currentGameRightAnswer],
[NSNumber numberWithInt:playerObject.currentGameType],[NSNumber numberWithInt:playerObject.nrOfType0Games],
[NSNumber numberWithInt:playerObject.type0Result], nil];
NSDictionary *newPlayerDict = [NSDictionary dictionaryWithObjectsAndKeys:objs, keyString, nil];
Try valueForKey:
You can only store one item per key in an NSDictionary. If you need story multiple items for the same key, you need to first add each of the items to an NSArray (or NSSet) that you instead then set as an object in your dictionary.
If might be useful if you posted the code that creates the dictionary.
Update: It looks like you are already doing this. So:
NSArray *myObjs=[playerDict objectForKey:keyString];
will get you your array. And this:
BOOL diffHard=[[myObjs objectAtIndex:0] boolValue];
BOOL diffMedium=[[myObjs objectAtIndex:1] boolValue];
Will get you the value you stored in the first and second objects of the array. Repeat it for the rest.

Retrieving data from a NSDictionary

I am not quite sure I understand how to do the following.
If I wanted to add e.g. an author and a title (key, value) to a dictionary. Fill that dictionary with data, then have another dictionary for say e.g. k = genre v = artist name and fill it with data.
Then I want to add the dictionaries to an array.
Firstly how is that done? and secondly, what if I allow the user to log their own entries. So I have to textfields on screen, when the user is done, it stores the fields as key value pair in a new dictionary e.g. user's dictionary.
What will I do later when trying to fill a tableview with the users entered data, I dont know the keys or values in that dictionary so how could I retrieve that data?
I mean let's say I want to load the user's dictionary from array index 2 and fill a tableview's cells with each dictionary entry, how is this done? Maybe a method like on an array(get entry.title at index blah blah ), get Key value in dictionary?
How else can one actually get loaded user entered data that they arent aware of the values?
Regards
Add author and title to a dictionary (assuming they're objects that already exist - likely NSString instances in your case):
NSMutableDictionary *books = [[NSMutableDictionary alloc] initWithCapacity:10];
[books setObject:title forKey:author];
Same thing for genre/artist:
NSMutableDictionary *music = [[NSMutableDictionary alloc] initWithCapacity:10];
[books setObject:artist forKey:genre];
Then put them in an array:
NSArray *theArray = [NSArray arrayWithObjects:books, music, nil];
Then to read out the stuff at array index 2:
id key;
NSDictionary *theDictionary = [theArray objectAtIndex:2];
id value;
for (key in [theDictionary allKeys])
{
value = [theDictionary objectForKey:key];
// do something with the value
}
You can get an NSArray of keys in the dictionary using allKeys. Then you can retrieve the values using objectForKey:
for (id key in [myDict allKeys]) {
NSLog(#"key: %#, value: %#", key, [dictionary objectForKey:key]);
}

Algorithm: array of arrays in Cocoa Touch (perhaps using NSCountedSet)

This one is a bit tedious in as far as explaining, so here goes. I'm essentially populating a tableView on the iPhone with multiple sections, and potentially multiple rows per section. To my understanding, it's best to have an array of arrays so that you can simply determine how many sections one has by sending a message to the top level array of count, then for rows per section, doing the same for the inner array(s). My data is in the form of a dictionary. One of the key/value pairs in the dictionary determines where it will be displayed on the tableView. An example is the following:
{
name: "bob",
location: 3
}
{
name: "jane",
location: 50
}
{
name: "chris",
location: 3
}
In this case I'd have an array with two subarrays. The first subarray would have two dictionaries containing bob and chris since they're both part of location 3. The second subarray would contain jane, since she is in location 50. What's my best bet in Cocoa populate this data structure? A hash table in C would probably do the trick, but I'd rather use the classes available in Cocoa.
Thanks and please let me know if I need to further clarify.
The following code works: (edit: added my initialization code)
NSArray * arrayOfRecords = [NSArray arrayWithObjects:
[NSDictionary dictionaryWithObjectsAndKeys:
#"bob", #"name",
[NSNumber numberWithInt:3], #"location", nil],
[NSDictionary dictionaryWithObjectsAndKeys:
#"jane", #"name",
[NSNumber numberWithInt:50], #"location", nil],
[NSDictionary dictionaryWithObjectsAndKeys:
#"chris", #"name",
[NSNumber numberWithInt:3], #"location", nil],
nil];
NSMutableDictionary * sections = [NSMutableDictionary dictionary];
for (NSDictionary * record in arrayOfRecords)
{
id key = [record valueForKey:#"location"];
NSMutableArray * rows = [sections objectForKey:key];
if (rows == nil)
{
[sections setObject:[NSMutableArray arrayWithObject:record] forKey:key];
}
else
{
[rows addObject:record];
}
}
NSArray * sortedKeys = [[sections allKeys] sortedArrayUsingSelector:#selector(compare:)];
NSArray * sortedSections = [sections objectsForKeys:sortedKeys notFoundMarker:#""];
NSLog(#"%#", sortedSections);
And NSDictionary is a hash table.
In Cocoa, it's best to use model objects rather than primitive collections, especially when using Bindings. The dictionaries should certainly be model object, and you may want to turn your inner arrays into model objects as well. (The outer array should stay an array.)
Cocoa Touch doesn't have Bindings, but I find (in Cocoa, as I don't program my iPhone) that model objects make things easier to think about and work with. I recommend you make model objects anyway.
(“Model” refers to Cocoa's “Model-View-Controller” pattern, in which Cocoa provides view and controller objects and you provide the model.)