I'm trying to add some vales to a NSMutableDictionary dynamically. However, using the following code, I'm adding values using the first letter as the key to a temporary dictionary and then finally adding it to my names dictionary but it just overwrites each value for it's corresponding key
NSMutableDictionary *dictionary = [[[NSMutableDictionary alloc] init] autorelease];
for (NSString *drugStr in listContents) {
NSString *substring = [drugStr substringToIndex:1];
[dictionary setValue:drugStr forKey:substring];
}
names = [[NSDictionary alloc] initWithDictionary:dictionary];
[dictionary release];
What am I doing wrong?
You should define your NSDictionary to use NSString as a key, and NSArray as a value.
Then you should just retrieve your value according to the given key. If the result is nil, then you need to create a new NSMutableArray, to which you add the value above. IF the result is not-nil, add the value to the array.
NSMutableDictionary *dictionary = [[[NSMutableDictionary alloc] init] autorelease];
for (NSString *drugStr in listContents) {
NSString *substring = [drugStr substringToIndex:1];
NSMutableArray *valueArray = (NSMutableArray*)[dictionary objectForKey:substring];
if(valueArray==nil){
NSMutableArray *newArray = [NSMutableArray arrayWithCapacity:5];
[newArray addObject:drugStr];
[dictionary setObject:newArray forKey:substring];
}else{
[valueArray addObject:drugStr];
}
}
names = [[NSDictionary alloc] initWithDictionary:dictionary];
[dictionary release];
Related
-(void) httpDataDidFinishLoadingWithData:(NSData *)theData
{
m_activityLoaded=NO;
temp=[[NSString alloc] initWithData:[dataLoader httpData]
encoding:NSUTF8StringEncoding];
NSLog(#"TEMP IS TEMP %#", temp);
NSDictionary *dict = [[NSDictionary alloc]init];
dict = [[temp JSONValue] objectForKey:#"location"];
NSDictionary *dict1 = [[NSDictionary alloc]init];
dict1 = [[temp JSONValue] objectForKey:#"wind"];
NSDictionary *dict2 = [[NSDictionary alloc]init];
dict2 = [dict1 objectForKey:#"direction"];
NSDictionary *dict3 = [[NSDictionary alloc]init];
dict3 = [[temp JSONValue] objectForKey:#"atmosphere"];
NSDictionary *dict4 = [[NSDictionary alloc]init];
dict4 = [[temp JSONValue] objectForKey:#"condition"];
NSDictionary *dict5 = [[NSDictionary alloc]init];
dict5 = [dict4 objectForKey:#"text"];
NSDictionary *dict6 = [[NSDictionary alloc]init];
dict6 = [dict4 objectForKey:#"code"];
NSDictionary *dict7 = [[NSDictionary alloc]init];
dict7 = [dict4 objectForKey:#"temperature"];
temperatureLabel.text = [dict4 objectForKey:#"temperature"];
}
Crash occurs at temperatureLabel.text = [dict4 objectForKey:#"temperature"];
I dont know man, Data is exactly printed in the console, but crashing at UILABEL(temperatureLabel). Help me out, thanks in advance
if you look at the error you are getting it is telling you that the object return for the key temperature is not a NSString or NSDictionary but a NSNumber.
Give this a try:
-(void) httpDataDidFinishLoadingWithData:(NSData *)theData {
m_activityLoaded=NO;
temp=[[NSString alloc] initWithData:[dataLoader httpData]
encoding:NSUTF8StringEncoding];
NSLog(#"TEMP IS TEMP %#", temp);
NSDictionary *dict = [[temp JSONValue] objectForKey:#"location"];
NSDictionary *dict1 = [[temp JSONValue] objectForKey:#"wind"];
NSDictionary *dict2 = [dict1 objectForKey:#"direction"];
NSDictionary *dict3 = [[temp JSONValue] objectForKey:#"atmosphere"];
NSDictionary *dict4 = [[temp JSONValue] objectForKey:#"condition"];
NSDictionary *dict5 = [dict4 objectForKey:#"text"];
NSDictionary *dict6 = [dict4 objectForKey:#"code"];
NSNumber *temperature = [dict4 objectForKey:#"temperature"];
temperatureLabel.text = [NSString stringWithFormat:#"%#", temperature];
}
You might want to look at NSNumberFormatter for formatter the temperature with something like: °F or °C.
Are you sure that your object is of NSString class?
Try putting in something like:
if([[dict4 objectForKey:#"temperature"] isKindOfClass:[NSString class]])
NSLog(#"lalala");
If it does not get logged to the console it means that your object is not an NSString and you could try something like:
temperatureLabel.text = [NSString stringWithFormat:#"%#", [dict4 objectForKey:#"temperature"]];
You should change the %# according to the kind of object you have stored in your dictionnary.
Your dictionary contains an NSNumber instance and you are assigning that to a property of type NSString. The crash message is your tip off there. Use stringValue or some other way to get the number's data into string form.
simple question, I need to structure data in the following format:
UserID:
1 {
Name = Bob
Surname = Hope
}
2 {
...
I can used an NSMutableDictionary to add a single layer with keys, but I am unable to create a child associate with a certain key.
I have tried creating a mutable dictionary and assigning that to a key:
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
NSArray *keys = [[NSArray alloc] initWithObjects:#"Name", #"Surname", nil];
NSArray *details = [[NSArray alloc] initWithObjects:#"Bob",#"Hope", nil];
NSDictionary *person = [[NSMutableDictionary alloc] initWithObjects:details forKeys:keys];
[dic setValue:#"1" forKey:#"id"];
[[dic objectForKey:#"id"] setDictionary: person];
I think it is better to use an array of dictionaries, each dictionary representing a user.
NSMutableArray *users= [[NSMutableArray alloc] init];
NSArray *keys = [[NSArray alloc] initWithObjects:#"Name", #"Surname", nil];
NSArray *details = [[NSArray alloc] initWithObjects:#"Bob",#"Hope", nil];
NSDictionary *person = [[NSMutableDictionary alloc] initWithObjects:details forKeys:keys];
[users addObject:person];
u can also set the objects for dictionary in this way
[dic setObject:person forKey:#"id"];
A quick question about NSArrays and NDictionarys.
I have and NSArray containing NSDictionarys.
The NSDictionary contain a date and a string.
What I would like to do is end up with an NSDictionary with keys dates and values arrays of strings that are on that date.
What would be the best way to do this
NSMutableDictionary *result = [NSMutableDictionary dictionary];
for (NSDictionary *dict in array) {
NSDate *date = [dict objectForKey:#"dateKey"];
NSString *string = [dict objectForKey:#"stringKey"];
NSMutableArray *stringsWithDate = [result objectForKey:date];
if (!stringsWithDate) {
stringsWithDate = [NSMutableArray array];
[result setObject:stringsWithDate forKey:date];
}
[stringsWithDate addObject:string];
}
Note that NSDate is not a "calendar date", so the same day with a different time will be considered as a distinct date in your result dictionary.
As I do not see any reasonable motivation for doing this, let's call it code golf.
NSMutableArray *dates = [NSMutableArray array];
NSMutableArray *strings = [NSMutableArray array];
for (NSDictionary *dict in dictArray) {
[dates addObject:[dict objectForKey:#"date"]];
[strings addObject:[dict objectForKey:#"string"]];
}
NSArray *datesArray = [[NSArray alloc] initWithArray:dates];
NSArray *stringsArray = [[NSArray alloc] initWithArray:strings];
I'm getting data from a database and I need to add the string field value and the record id.
However, I need this to work with some existing code...
I'm replacing this (see code below) and getting data from my database.
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
self.allCategories = dict;
[dict release];
This is the file it loads...
But needs to work with these key and value search functions.
- (void)resetSearch {
NSMutableDictionary *allCategoriesCopy = [self.allCategories mutableDeepCopy];
self.Categories = allCategoriesCopy;
[allCategoriesCopy release];
NSMutableArray *keyArray = [[NSMutableArray alloc] init];
[keyArray addObject:UITableViewIndexSearch];
[keyArray addObjectsFromArray:[[self.allCategories allKeys]
sortedArrayUsingSelector:#selector(compare:)]];
self.keys = keyArray;
[keyArray release];
}
.
- (void)handleSearchForTerm:(NSString *)searchTerm {
NSMutableArray *sectionsToRemove = [[NSMutableArray alloc] init];
[self resetSearch];
for (NSString *key in self.keys) {
NSMutableArray *array = [Categories valueForKey:key];
NSMutableArray *toRemove = [[NSMutableArray alloc] init];
for (NSString *name in array) {
if ([name rangeOfString:searchTerm
options:NSCaseInsensitiveSearch].location
== NSNotFound)
[toRemove addObject:name];
}
if ([array count] == [toRemove count])
[sectionsToRemove addObject:key];
[array removeObjectsInArray:toRemove];
[toRemove release];
}
[self.keys removeObjectsInArray:sectionsToRemove];
[sectionsToRemove release];
[table reloadData];
}
Keep getting an error from this code...
NSDictionary *arrayTmp= [[NSDictionary alloc] init];
... loop records
int cid = sqlite3_column_int(statementTMP, 0);
NSString *category = [[NSString alloc]
initWithUTF8String:(char *)sqlite3_column_text(statementTMP, 1)];
[arrayTmp setObject:category forKey:[NSString stringWithFormat:#"%i", cid]];
Error caused by line above
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSCFString count]: unrecognized selector sent to instance 0x4d4c500' * Call stack at first throw *
... end loop
self.allCategories = arrayTmp;
[arrayTmp release];
The error message says you are sending 'count' to an instance of NSString.
My guess is that the plist at 'path' (the plist file) has a string as one of the values. As you iterate through 'Categories' you expect each value to be an array (i.e. 'NSMutableArray *array = [Categories valueForKey:key];') and send that value a 'count' message.
One of the objects you expect to be an array is a string.
setValue is key-value coding method. You should use setObject:forKey: instead.
arrayTmp should be inited with [[NSMutableDictionary alloc] init].
First of all, you're using wrong method:
[arrayTmp setValue:category forKey:[NSString stringWithFormat:#"%i", cid]];
which method used for key-value coding (you can find more about KVO here).
The method you're looking for is:
[arrayTmp setObject:category forKey:[NSString stringWithFormat:#"%i", cid]];
Moreover, you should NSMutableDictionary. The NSDictionary you're using does not support mutation. (you can find more info on NSMutableDictionary here).
Cheers,
Pawel
I want to add content of NSArray's to NSDictionary r NSMultDictionary.
I have NSDictionary(empty), and I have NSArray with content and I have to store NSArray content in NSDictionary.
How can I do this?
You can add content of NSArray to NSDictionary by using following code.
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
for(int i=0; i<[Array count]; i++){
[dic setObject:[Array objectAtIndex:i] forKey:[NSString stringWithFormat:#"%d",i]];
}
The dic is the dictionary, you can use that.
Or else you can add whole array as one object in the dictionary as
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
[dic setObject:Array forKey:#"array"];
#Nandakishore suppose you have an array eg:-myArray
NSDictionary *A = [NSDictionary dictionaryWithObject:myArray forKey:#"Key"];
Now this dictionary object(A) has all the content of the myArray......now do what u wanna do with your dictionary
I hope this may help you!