NSMutableDictionary confused over how to use keys with certain code? - iphone

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

Related

Initialize multiple objects with different name

How can I Initialize and allocate multiple objects with different name and pass it to the NSArray. from Below code the object is initialized once in loop and I need to initialized multiple times as per the For loop will go with different name..and then pass it to NSArray.please check the code below..
when For loop will start means i=0 ..initialized item would betempItemi
now next time when i=1 and i=2 the tempItemi name will be same .how can i change this with in loop..and pass it to NSArray *items
for (int i = 0; i< [Array count]; i++)
{
id object = [Array objectAtIndex:i];
if ([object isKindOfClass:[NSDictionary class]])
{
NSDictionary *objDict = (NSDictionary *)object;
ECGraphItem *tempItemi = [[ECGraphItem alloc]init];
NSString *str = [objDict objectForKey:#"title"];
NSLog(#"str value%#",str);
float f=[str floatValue];
tempItemi.isPercentage=YES;
tempItemi.yValue=f;
tempItemi.width=30;
NSArray *items = [[NSArray alloc] initWithObjects:tempItemi,nil];
//in array need to pass all the initialized values
[graph drawHistogramWithItems:items lineWidth:2 color:[UIColor blackColor]];
}
}
Why dont you just make the array mutable and then add the object each time like this:
NSMutableArray *items = [[NSMutableArray alloc] init];
// a mutable array means you can add objects to it!
for (int i = 0; i< [Array count]; i++)
{
id object = [Array objectAtIndex:i];
if ([object isKindOfClass:[NSDictionary class]])
{
NSDictionary *objDict = (NSDictionary *)object;
ECGraphItem *tempItemi = [[ECGraphItem alloc]init];
NSString *str = [objDict objectForKey:#"title"];
NSLog(#"str value%#",str);
float f=[str floatValue];
tempItemi.isPercentage=YES;
tempItemi.yValue=f;
tempItemi.width=30;
[items addObject: tempItemi];
//in array need to pass all the initialized values
}
}
[graph drawHistogramWithItems:items lineWidth:2 color:[UIColor blackColor]];
Anyways items in your original code will be reinitializing each time and you are drawing a new histogram each time so your code won't work... This should work...
The code you have written is ok but,
NSArray *items will always contain only one item at each loop.
just declare that outside for loop as NSMutableArray,
and go with the same code you are using.
As you said you want to make variable dynamically as
ECGraphItem *tempItemi = [[ECGraphItem alloc]init];
here i will be changing in the loop,
You can create a NSDictionary with key/value as per with your tempItem1/2/3/4.... as key and save values by alloc/init.
Then instead of a variable tempItem32, you will be using [dict valueForKey:#"tempItem32"].
EDIT:
Check this example if this may come handy
NSMutableDictionary *dict=[NSMutableDictionary new];
for (int i=1; i<11; i++) {
NSString *string=[NSString stringWithFormat:#"string%d",i];
[dict setObject:[NSString stringWithFormat:#"%d", i*i] forKey:string];
}
NSLog(#"dict is %#",dict);
NSString *fetch=#"string5";
NSLog(#"val:%#, for:%#",[dict valueForKey:fetch],fetch);

Problem with UISearchBar and NSMutableArray

I have a tableview with a search bar. I want to search my whole core data database.
I loaded everything into an array here:
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:#"Entity" inManagedObjectContext:managedObjectContext];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:entityDescription];
NSError *error = nil;
NSArray *array = [managedObjectContext executeFetchRequest:request error:&error];
self.myArray = array;
I'm then searching using this method but getting an error:
- (void) searchTableView {
NSString *searchText = searchBar.text;
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
for (NSDictionary *dictionary in myArray)
{
NSString *value = [dictionary objectForKey:#"name"];
[searchArray addObject:value];
}
for (NSString *sTemp in searchArray)
{
NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
[copyListOfItems addObject:sTemp];
}
[searchArray release];
searchArray = nil;
}
But when I search, I get the crash here:
MedicalCode *code = [self.copyListOfItems objectAtIndex:indexPath.row];
cell.codeLabel.text = code.description;
Error:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ICD9Disease objectForKey:]: unrecognized selector sent to instance 0x1be6e0'
You are getting the error because you are asking for an object, but you're trying to set a string, in the line:
NSString *value = [dictionary objectForKey:#"name"];
Since you're getting a string, not an object, what you need to use is valueForKey:
NSString *value = [dictionary valueForKey:#"name"];
It looks like you're expecting the fetch request to return dictionaries, but it's actually returning instances of the class ICD9Disease.

Obj-C, iOS, can someone explain this NSMutableArray code and suggest how I can sort on the name?

Can someone exlain this code in detail and suggest how I can sort on the name?
- (void)handleSearchForTerm:(NSString *)searchTerm {
selectButton.enabled = NO;
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];
}
- (void)handleSearchForTerm:(NSString *)searchTerm {
selectButton.enabled = NO;
NSMutableArray *sectionsToRemove = [[NSMutableArray alloc] init]; //creating an mutable array, which can be altered in progress.
[self resetSearch]; //calling some other method not displayed in the code here
for (NSString *key in self.keys) { //for each key,
NSMutableArray *array = [Categories valueForKey:key]; //you get the key's category
NSMutableArray *toRemove = [[NSMutableArray alloc] init]; //and initialize the array for items you wish to remove
for (NSString *name in array) { //then, for each name
if ([name rangeOfString:searchTerm options:NSCaseInsensitiveSearch].location == NSNotFound)
[toRemove addObject:name];
//you check if the name is in range of the searchterm, with which you call this function
//if you don't find it, you add it to the removal list
}
if ([array count] == [toRemove count])
[sectionsToRemove addObject:key]; //if you haven't found any name, it means you've added all the names in the toRemove array
[array removeObjectsInArray:toRemove]; //that means the count of both arrays are the same
[toRemove release]; //so you remove that section entirely, since there is no result there
}
[self.keys removeObjectsInArray:sectionsToRemove]; //you remove all the keys which aren't found
[sectionsToRemove release]; //leaving you the keys which are found
[table reloadData]; //you reload the table with the found results only
}
I hope it all made sense, I did my best commenting it ;)
Good luck.

Values not appending to my NSMutableDictionary

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

NSCFString countByEnumeratingWithState:objects:count: ERROR while searching NSMutableArray

I have the following situation where
I have an NSMutableArray filled with an xml file which I want to search.
When I enter something in the search field I get this Error:
-[NSCFString countByEnumeratingWithState:objects:count:]: unrecognized selector sent to instance 0x5b388b0
What does it means and how can I fix it??
I suppose the error is somewhere around here.
- (void)searchTableView{
searchedList = [[NSMutableArray alloc] init];
NSLog(#"new list %#", searchedList);
NSString *searchText = searchBar.text;
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
for (NSDictionary *dictionary in list) {
NSArray *array = [dictionary objectForKey:#"TITLE"];
[searchArray addObjectsFromArray:array];
}
for (NSString *TempArray in searchArray) {
NSRange titleResults = [TempArray rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResults.length > 0)
[searchedList addObject:TempArray];
}
[searchArray release];
searchArray = nil;
}
it means you are calling a method designed for an NSArray (countByEnumeratingWithState:objects:count on a NSString.
I don't know ifthis code is copy/paste from yours, but if so, at the end where you use [searchList addObject:TempArray] you don't have an object named searchList.
Also, work on your naming conventions. big time.