How to get index value of search data in table view in iPhone - iphone

I am using a tableview controller with the searchbar. I want to get all index positions of the array elements which are related to a search result of any string from a table.
For example: If I have an array containing the following: #"sau",#"jain",#"abc",#"sau",#"zyx" and I search for 'sau' then I want it to output index 0 and 3.
How might I achieve this?

Try following code:
NSArray *array = #[ #"sau", #"jain", #"abc", #"sau", #"zyx" ];
NSString *searchString = #"sau";
NSIndexSet *result = [array indexesOfObjectsPassingTest:^BOOL(NSString *string, NSUInteger idx, BOOL *stop) {
NSRange searchStringRange = [string rangeOfString:searchString options:NSCaseInsensitiveSearch];
return searchStringRange.length > 0;
}];
NSLog(#"Result indexes: %#", result);
Console output is Result indexes: <NSIndexSet: 0x8a80c50>[number of indexes: 2 (in 2 ranges), indexes: (0 3)]
Tune code within the block to match you search logic
Edit
Or to process objects on one by one basis
NSArray *array = #[ #"sau", #"jain", #"abc", #"sau", #"zyx" ];
NSString *searchString = #"sau";
[array enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL *stop) {
BOOL searchCondition = [obj isEqualToString:searchString];
if (!searchCondition) return;
// You logic to process objects passing the search condition
}];

Related

How to compare last three data of MutableArray with String?

In my application i have got data in Mutable array like this,
MutableArray1:(
"22.298166 , 73.165809",
"22.300598 , 73.167183",
"22.298101 , 73.166188",
"22.298128 , 73.166194"
"22.298130 , 73.166194"
)
I want to compare a NSString with data "22.298130 , 73.166194" with last three data of MutableArray1.
Please suggest me how can i do that?
if([Array1 count]>3)
{
for (int i = [Array1 count] - 4; i < [Array1 count]; i++) {
if ([[Array1 objectAtIndex:i] isEqualToString:#"22.298130 , 73.166194"]) {
NSLog (#"True");
//Write your Code Here
}
}
}
NSArray *array = #[ #"22.298166 , 73.165809",
#"22.300598 , 73.167183",
#"22.298101 , 73.166188",
#"22.298128 , 73.166194",
#"22.298130 , 73.166194"];
If you just need to know, if it is inside the array:
NSString *searchString = #"22.298130 , 73.166194";
BOOL found = [[array subarrayWithRange:NSMakeRange([array count]-3, 3)] containsObject:searchString];
NSLog(#"%#", (found) ? #"YES" : #"NO");
if you need to know the index, you can do
[[array subarrayWithRange:NSMakeRange([array count]-3, 3)] enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL *stop) {
if ([obj isEqualToString:searchString]) {
*stop = YES; //avoid further loops, if we had a positive hit.
NSLog(#"%lu %lu", idx, [array count]-3+idx); //index in subarray and in original array
};
}];

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
)

NSArray full of NSDictionaries. How to find index of object?

I have an array which is filled with NSDictionaries. I want to find the index of one of the dictionary, but what I know about this dictionary is only a value for key #"name".
How do I do it ?
Find index of first dictionary in theArray whose value for #"name" is theValue:
NSUInteger index = [theArray indexOfObjectPassingTest:
^BOOL(NSDictionary *dict, NSUInteger idx, BOOL *stop)
{
return [[dict objectForKey:#"name"] isEqual:theValue];
}
];
index will be NSNotFound if no matching object is found.
NSArray *temp = [allList valueForKey:#"Name"];
NSInteger indexValue = [temp indexOfObject:YourText];
NSString *name = [[allList objectAtIndex:indexValue] valueForKey:#"Name"]

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 get indices of NSArray using something like indexOfObject?

I can use [NSArray indexOfObject: NSString] to get an index of my search for 1 item. But what can I use or do to get an array of returned indices from my search?
thanks
To get multiple indices, you can use indexesOfObjectsPassingTest::
// a single element to search for
id target;
// multiple elements to search for
NSArray *targets;
...
// every index of the repeating element 'target'
NSIndexSet *targetIndices = [array indexesOfObjectsPassingTest:^ BOOL (id obj, NSUInteger idx, BOOL *stop) {
return [obj isEqual:target];
}];
// every index of every element of 'targets'
NSIndexSet *targetsIndices = [array indexesOfObjectsPassingTest:^ BOOL (id obj, NSUInteger idx, BOOL *stop) {
return [targets containsObject:obj];
}];
Support for blocks were added in iOS 4. If you need to support earlier versions of iOS, indexesOfObjectsPassingTest: isn't an option. Instead, you can use indexOfObject:inRange: to roll your own method:
#interface NSArray (indexesOfObject)
-(NSIndexSet *)indexesOfObject:(id)target;
#end
#implementation NSArray (indexesOfObject)
-(NSIndexSet *)indexesOfObject:(id)target {
NSRange range = NSMakeRange(0, [self count]);
NSMutableIndexSet *indexes = [[NSMutableIndexSet alloc] init];
NSUInteger idx;
while (range.length && NSNotFound != (idx = [self indexOfObject:target inRange:range])) {
[indexes addIndex: idx];
range.length -= idx + 1 - range.location;
range.location = idx + 1;
}
return [indexes autorelease];
}
#end
If you don't have access to indexOfObjectsPassingTest, as #outis recommends, you could use indexOfObject:inRange: and loop over the results, updating the range to start after the last result finished, and updating the results into your own NSIndexSet, or NSMutableArray, etc.