How to Filter Cells in AQGridView with UISearchBar - iphone

i'm going crazy on this problem:
I'm using AQGridView for show some image from an array that i retrieve from SQLite but i'm not able to filter the Grid with a UISearchBar that i put in the TitleView of a Detail zone in a SplitViewController. Can u help me with some logic passage or with an example?
Thanks!

SOLVED!
Recalculated the array _icons after removed all objects..
[_icons removeAllObjects];
searching = YES;
NSInteger numeroElem = [subcatList getSize];
for ( NSUInteger i = 0; i < numeroElem; i++ )
{
NSDictionary *itemAtIndex = (NSDictionary *)[subcatList objectAtIndex:i];
NSString *titolo_cat = [itemAtIndex objectForKey:#"titolo"];
NSComparisonResult result = [titolo_cat compare:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])];
if (result == NSOrderedSame)
{
ETC ETC.......
[_icons addObject: image];
}
};

Related

sqlite search in multiple column

I have a simple database in iPad Application having couple of tables.
The UI displays the table data properly in a master-detail view controller. I want to add a search feature which will search for the given text in all the field/columns of all the tables and give the result.
One crude way is to write a select query using where clause for each columns. But I believe there will be some proper way for that.
Or is it possible to search the UITableView itself and refresh the data ?
Regards,
nirav
Code for searching in Table
- (void) searchTableView {
NSString *searchText = searchBar.text;
if([searchText length] == 0)
{
[searchArr addObjectsFromArray:userArr];
}
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
for (int i=0; i<[userArr count]; i++) {
NSString *sTemp = [[userArr objectAtIndex:i] objectForKey:#"name"];
NSRange titleResultsRange = [[sTemp lowercaseString] rangeOfString:[searchText lowercaseString]];
if(titleResultsRange.location != NSNotFound && titleResultsRange.location == 0)
{
[searchArr addObject:[userArr objectAtIndex:i]];
}
}
searchArray = nil;
}

Search String into NSArray based on charcters order?

My Problem Scenario is like this. I have an NSMutableArray ( Every Object is Nsstring). I have a UItextField ( as Client said) for Search.
I want know how to Search String into NSMutableArray like this
if I type A into textfield only those Content come from NSMutableArray which start From A.
if I type AB into TextField only those Content Comes from NSMutableArray which is started from AB..
....
I am Trying NSRange Concept I like share Mycode
~
for (int i=0; i<[[localTotalArrayForAwailable objectForKey:#"PUNCH"] count]; i++)
{
NSString *drinkNamePuch= [[[localTotalArrayForAwailable objectForKey:#"PUNCH"] objectAtIndex:i] drinkNames];
NSRange titleResultsRange = [drinkNamePuch rangeOfString:searchText options:( NSCaseInsensitiveSearch)];
if (titleResultsRange.length>0)
{
[searchArraypuch addObject:[[localTotalArrayForAwailable objectForKey:#"PUNCH"] objectAtIndex:i]];
[copyListOfItems setValue:searchArraypuch forKey:#"PUNCH"];
}
}
~
Based on this code search not working proper as i need.
Thanks
If you're trying to find all of the strings that match your searchText from the beginning, then you should check:
if ( titleresultsRange.location == 0 )
Other than that, I am not sure what is "not working proper", you need to provide a better explanation of what your expected results are, and what your actual results are.
Do this;
NSPredicate* predicate = [NSPredicate predicateWithFormat:#"SELF BEGINSWITH[cd] %#", searchText];
NSArray* filteredStrings = [[localTotalArrayForAwailable objectForKey:#"PUNCH"] filteredArrayUsingPredicate:predicate];
In filteredStrings you got all the strings that begins with searchText.
You might find Predicate Programming Guide helpful.
try this logic....it is working
NSMutableArray *arr = [[NSMutableArray alloc]initWithObjects:#"aa",#"bbb",#"bb",#"cc",#"dd",#"ee",#"ff",#"gg",#"hh",#"ii", nil];
NSMutableArray *arrNew = [[NSMutableArray alloc]init];
NSString *strSearch = #"cccc";
int k = strSearch.length;
for (int i=0; i<[arr count]; i++) {
for (int j=0; j<k; j++) {
if (k<=[[arr objectAtIndex:i] length]) {
if ([strSearch characterAtIndex:j] != [[arr objectAtIndex:i]characterAtIndex:j]) {
break;
}
else if(j == k-1){
[arrNew addObject:[arr objectAtIndex:i]];
}
}
}
}
NSLog(#"%#",[arrNew description]);
You can use these methods, which are provided by NSArray/NSMutableArray:
In NSArray see section "Finding Objects in an Array" for filtering methods starting with "indexesOfObjects...", e.g. indexesOfObjectsPassingTest:
In NSArray see section "Deriving New Arrays" for the method filteredArrayUsingPredicate:
In NSMutableArray there is a method filterUsingPredicate:
For narrowing the results you can continue applying the filtering consecutively to the filtered arrays or index sets.
Example with indexesOfObjectsPassingTest: using a block:
NSArray *strings = [NSArray arrayWithObjects:#"A", #"a", #"aB", #"AbC", #"Bag", #"Babc", #"baCK", #"", #"dba", nil];
NSString *searchString = #"Ab";
BOOL (^startsWithPredicate)(id, NSUInteger, BOOL*) = ^BOOL (id obj, NSUInteger idx, BOOL *stop) {
NSString *string = (NSString *) obj;
NSRange range = [string rangeOfString:searchString options:NSCaseInsensitiveSearch];
return (range.location == 0);
};
NSIndexSet *indexSet = [strings indexesOfObjectsPassingTest:startsWithPredicate];
NSLog(#"Strings found: %#", [strings objectsAtIndexes:indexSet]);
Output:
Strings found: (
aB,
AbC
)

Search index of NSMutableArray

I need to search the index of a string from NSMutableArray. I have implemented the code & which works perfect, but I need to increase the searching speed than this.
I have used the following code:
NSIndexSet *indexes = [mArrayTableData indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop){
NSString *s = (NSString*)obj;
NSRange range = [s rangeOfString: txtField.text options:NSCaseInsensitiveSearch];
if(range.location == 0)//
return range.location != NSNotFound;
return NO;
}];
NSLog(#"indexes.firstIndex =%d",indexes.firstIndex);
There is a method indexOfObject
NSString *yourString=#"Your string";
NSMutableArray *arrayOfStrings = [NSMutableArray arrayWithObjects: #"Another strings", #"Your string", #"My String", nil];
NSInteger index=[arrayOfStrings indexOfObject:yourString];
if(NSNotFound == index) {
NSLog(#"Not Found");
}
If you only want one index (or just the first one if there are multiples), you can use the singular version of the method you posted. You also don't need the if clause:
NSInteger index = [mArrayTableData indexOfObjectPassingTest:^BOOL(NSString *obj, NSUInteger idx, BOOL *stop){
return [obj.lowercaseString isEqualToString:txtField.text.lowercaseString];
}];
If you want to find strings that start with the search string, just replace isEqualToString: with hasPrefix:. With a large search set, this appears to be about twice as fast as the method you posted.

How to Search 2nd word in a string of array using UISearchBar?

I have to search a word in an array using UISearchBar. for example i have "Chicken Salad" string in an array at index 2. now if want to search it using last word "Salad" then what should i do?
for the time i am using this code and it is working good but if you search from first word.
(appDelegate.isAirlineSelection == YES) {
for (int i = 0; i < [menuArray count]; i++) {
if ([[[[menuArray objectAtIndex:i] itemName] uppercaseString] hasPrefix:search]||[[[[menuArray objectAtIndex:i] itemName] uppercaseString] hasSuffix:search]) {
[tableMenuArray addObject:[menuArray objectAtIndex:i]];
NSLog(#"Found");
}
}
Kindly help me
try this way, It'll search even between the words:
for(NSString *name in menuArray)
{
if ([name rangeOfString:search options:NSLiteralSearch|NSCaseInsensitiveSearch].location != NSNotFound)
[tableMenuArray addObject:name];
NSLog(#"Found");
}
First you should break your array name in two parts and create two arrays, then you can easily use search bar for second array and can find exact result ,what do you want.
for (NSString *name in lastnames)
{
NSComparisonResult result = [name compare:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])];
if (result == NSOrderedSame)
{
[searchedNames addObject:name];
}
}

Sorting an NSArray like the MPMediaPickerController/iPod Library

I'm developing a custom UIViewController for iPhone that emulates a subset of the MPMediaPickerController for files in my application's local documents directory. In particular, I'm attempting to re-create the Songs tab. I've been successful in creating my new controller, except I can't get the song titles to sort like they do in the iPod Library or the MPMediaPickerController. Here's an example of how the song names need to be sorted:
Awesome Song Title
Cool Song
The Darkest Song Ever
My Song Title
A Really Cool Song
Why Me?
4 Hours Wasted
As you can see, the sorting excludes the leading articles in the song titles and also places songs that begin with a numeric value at the end of the list. Can anyone suggest an efficient sorting function that takes these tules into account?
Since it looks like no one could offer up a solution, I thought I would post the solution I came up with. First, I created a model for my data:
#interface MyModel : NSObject
{
NSString* _value;
NSString* _sortableValue;
}
#property (nonatomic,copy) NSString* value;
- (NSString*)sortableValue;
- (NSString*)comparableString:(NSString*)str;
#end
They key to the model is the comparableString method, which gets used to create the sortableValue. Here's the implementation of the model:
#implementation MyModel
#synthesize value=_value;
-(void)dealloc
{
[_value release];
[_sortableValue release];
[super dealloc];
}
- (void)setValue:(NSString*)value
{
[_value release];
_value = [value copy];
[_sortableValue release];
_sortableTValue = nil;
}
- (NSString*)sortableValue
{
if (_sortableValue == nil)
_sortableValue = [[self comparableString:_value] retain];
return _sortableValue;
}
- (NSString*)comparableString:(NSString*)str
{
if (str == nil)
return nil;
else if ([str length] == 0)
return [NSString stringWithString:str];
NSCharacterSet* numbersSet = [NSCharacterSet decimalDigitCharacterSet];
if ([str rangeOfCharacterFromSet:numbersSet options:0 range:NSMakeRange(0, 1)].location != NSNotFound)
return [NSString stringWithString:str];
NSRange range = NSMakeRange(0, [str length]);
if ([str compare:#"a " options:(NSAnchoredSearch|NSCaseInsensitiveSearch) range:NSMakeRange(0, 2)] == NSOrderedSame)
range.location = 2;
else if ([str compare:#"an " options:(NSAnchoredSearch|NSCaseInsensitiveSearch) range:NSMakeRange(0, 3)] == NSOrderedSame)
range.location = 3;
else if ([str compare:#"the " options:(NSAnchoredSearch|NSCaseInsensitiveSearch) range:NSMakeRange(0, 4)] == NSOrderedSame)
range.location = 4;
range.length -= range.location;
NSCharacterSet* lettersSet = [NSCharacterSet letterCharacterSet];
NSUInteger letterOffset = [str rangeOfCharacterFromSet:lettersSet options:0 range:range].location;
if (letterOffset == NSNotFound)
return [NSString stringWithString:str];
letterOffset -= range.location;
range.location += letterOffset;
range.length -= letterOffset;
return [str substringWithRange:range];
}
#end
In addition to the removing the leading articles from the string, it also removes any leading non-letter characters. I have a song in my iPod library entitled "$ell Your $oul", which ends up in the E section in the MPMediaPickerController. I'm not sure that's what I would have done had I crated the initial sorting algorithm, but I was going to consistency with the MPMediaPickerController, so there you go.
The final piece of the puzzle is the UILocalizedIndexedCollation class. This handy little helper class will help you sort your data to make supplying it to a UITableView via a UITableViewDataSource a piece of cake. Here's a snippet on how to use the UILocalizedIndexedCollation class in conjunction with the model:
// tableData will contain an NSArray for each populated section in the table view
NSMutableDictionary* tableData = [NSMutableDictionary dictionary];
NSMutableArray* myArray = [NSMutableArray array];
// Populate myArray with instances of MyModel
UILocalizedIndexedCollation* indexer = [UILocalizedIndexedCollation currentCollation];
for (MyModel* data in myArray)
{
NSInteger index = [indexer sectionForObject:data collationStringSelector:#selector(sortableValue)];
NSNumber* key = [[NSNumber alloc] initWithInteger:index];
NSMutableArray* array = [tableData objectForKey:key];
if (array == nil)
{
array = [NSMutableArray new]; // Will be released after creating a sorted array in the following section
[tableData setObject:array forKey:key];
}
[array addObject:data];
[key release];
}
[tableData enumerateKeysAndObjectsUsingBlock:^(id key, id array, BOOL* stop)
{
NSMutableArray* sortedArray = [[indexer sortedArrayFromArray:array collationStringSelector:#selector(sortableValue)] mutableCopy];
[tableData setObject:sortedArray forKey:key];
[array release];
}];
One quick note about UILocalizedIndexedCollation (from Apple's documentation):
If the application provides a
Localizable.strings file for the
current language preference, the
indexed-collation object localizes
each string returned by the method
identified by selector.
So make sure you provide a Localizable.strings for each language you want to support, or your table view will only have sections A-Z and #.
It took me a while to work out all of the details on this, so I hope it becomes useful for other people. If you see any ways I can improve this, please let me know!
You may need to consider certain characters with accents as well such as è, é, ò, à, ù, ì.
So I slightly modified your code to incorporate this. Your code is a great contribution to all of us iphone developers
- (NSString*)comparableString:(NSString*)str
{
if (str == nil)
return nil;
else if ([str length] == 0)
return [NSString stringWithString:str];
NSCharacterSet* numbersSet = [NSCharacterSet decimalDigitCharacterSet];
if ([str rangeOfCharacterFromSet:numbersSet options:0 range:NSMakeRange(0, 1)].location != NSNotFound)
return [NSString stringWithString:str];
NSRange range = NSMakeRange(0, [str length]);
if ([str compare:#"a " options:(NSAnchoredSearch|NSCaseInsensitiveSearch) range:NSMakeRange(0, 2)] == NSOrderedSame)
range.location = 2;
else if ([str compare:#"an " options:(NSAnchoredSearch|NSCaseInsensitiveSearch) range:NSMakeRange(0, 3)] == NSOrderedSame)
range.location = 3;
else if ([str compare:#"the " options:(NSAnchoredSearch|NSCaseInsensitiveSearch) range:NSMakeRange(0, 4)] == NSOrderedSame)
range.location = 4;
range.length -= range.location;
NSCharacterSet* lettersSet = [NSCharacterSet letterCharacterSet];
NSUInteger letterOffset = [str rangeOfCharacterFromSet:lettersSet options:0 range:range].location;
if (letterOffset == NSNotFound)
return [NSString stringWithString:str];
letterOffset -= range.location;
range.location += letterOffset;
range.length -= letterOffset;
//my modification starts here.........
NSString * finalString = [str substringWithRange:range];
NSString * firstCharString = [finalString substringToIndex:1];
NSData * encodedData = [firstCharString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString * encodedString = [[NSString alloc] initWithBytes:[encodedData bytes] length:[encodedData length] encoding:NSASCIIStringEncoding];
if ([encodedString isEqualToString:#"?"]) {
return finalString;
}
NSString * finalProcessedString = [finalString stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:encodedString];
[encodedString release];
return finalProcessedString;
}