It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
My array is like
{
"Samsung Tab",
"Samsung Note",
"Samsung Galaxy",
"Samsung Galaxy Pro",
"Nokia Lumia",
"Nokia 5130",
"Sony Xperia"
}
Some thing like that. I have text box type GALAXY and click the button. I want to show only Samsung Galaxy , Samsung Galaxy Pro in next list view. Can anyone help me?.
Use predicate to filter an array like below
NSArray *arrayMobiles= [NSArray arrayWithObjects:#"Samsung Tab",#"Samsung Note", #"Samsung Galaxy", #"Samsung Galaxy Pro", #"Nokia Lumia", #"Nokia 5130",#"Nokia 5130",#"Sony Xperia", nil];
NSString *strSearchkey = #"GALAXY";
NSPredicate *containPred = [NSPredicate predicateWithFormat:#"SELF contains[cd] %#", strSearchkey];
NSArray *arrayFilter = [arrayMobiles filteredArrayUsingPredicate:containPred];
NSLog(#"%#",arrayFilter);
//output
"Samsung Galaxy",
"Samsung Galaxy Pro"
Take Two NSMutableArray and add one array to another array in ViewDidLoad method such like,
self.listOfTemArray = [[NSMutableArray alloc] init]; // array no - 1
self.ItemOfMainArray = [[NSMutableArray alloc] initWithObjects:#"YorArrayList", nil]; // array no - 2
[self.listOfTemArray addObjectsFromArray:self.ItemOfMainArray]; // add 2array to 1 array
And Write following delegate Method of UISearchBar
- (BOOL) textFieldDidChange:(UITextField *)textField
{
NSString *name = #"";
NSString *firstLetter = #"";
if (self.listOfTemArray.count > 0)
[self.listOfTemArray removeAllObjects];
if ([searchText length] > 0)
{
for (int i = 0; i < [self.ItemOfMainArray count] ; i = i+1)
{
name = [self.ItemOfMainArray objectAtIndex:i];
if (name.length >= searchText.length)
{
firstLetter = [name substringWithRange:NSMakeRange(0, [searchText length])];
//NSLog(#"%#",firstLetter);
if( [firstLetter caseInsensitiveCompare:searchText] == NSOrderedSame )
{
// strings are equal except for possibly case
[self.listOfTemArray addObject: [self.ItemOfMainArray objectAtIndex:i]];
NSLog(#"=========> %#",self.listOfTemArray);
}
}
}
}
else
{
[self.listOfTemArray addObjectsFromArray:self.ItemOfMainArray ];
}
[self.tblView reloadData];
}
}
Output Show in your Consol.
This code might helpful for you...thanks :)
This may help you
- (void)searchArrayFrom: (NSString *) matchString{
NSString *upString = [matchString uppercaseString];
if (searchArray){[searchArray release];searchArray = nil;}
searchArray = [[NSMutableArray alloc] init];
NSMutableArray *temp = [internalEvents copy];
for (int i=0;i<[temp count];i++)
{
NSString *str = [internalEvents objectAtIndex:i];
// Add everyone when there's nothing to match to
if ([matchString length] == 0)
{
[searchArray addObject:str];
continue;
}
// Add the person if the string matches
NSRange range = [[str uppercaseString] rangeOfString:upString];
if (range.location != NSNotFound) {
[searchArray addObject:str];
}
}
[temp release];
temp = nil;
[tblView reloadData];
}
You can use the below given function :
- (void)searchAutocompleteEntriesWithSubstring:(NSString *)substring
{
for (int i = 0; i < [yourArray count]; i++)
{
NSString *curString = [[yourArray objectAtIndex:i]lowercaseString];
NSString *searchString = [substring lowercaseString];
if ([curString rangeOfString:curStringSmall].location == NSNotFound)
{
}
else
{
//This means searched text is found in your array. you can store it in new array. Which will give you only the search criteria matched element.
}
}
}
You need to call this function on the click of your search button. Like :
-(void)searchButtonClicked
{
[self searchAutocompleteEntriesWithSubstring:txtSearch.text];
}
you might use the NSPrediction
NSString * SEARCH_KEYWORD = #"s";
NSMutableArray *array =
[NSMutableArray arrayWithObjects:#"Bill", #"Ben", #"Chris", #"Melissa", nil];
NSPredicate *sPredicate =
[NSPredicate predicateWithFormat:#"SELF contains[c] '%#'", SEARCH_KEYWORD];
[array filterUsingPredicate:sPredicate];
// array now contains { #"Chris", #"Melissa" }
Related
In my app, i have a search bar in my contact list page tableview. now my code searches the list based on any letter even if the search text is at the middle of the firstname or lastname. But i want it to search only from the beginning. For example., the word "sh" should pull only "Shiva", "Sheela", etc., but not "sathish", "suresh" etc., can anyone help me on this?
and my code is
- (void)searchBar:(UISearchBar *)searchBar
textDidChange:(NSString *)searchText
{
//---if there is something to search for---
if ([searchText length] > 0)
{
isSearchOn = YES;
canSelectRow = YES;
self.ContactTableview.scrollEnabled = YES;
searchTextValue = searchText;
[searchResult removeAllObjects];
for (NSString *str in ContactArray)
{
NSRange range = [str rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(range.location != NSNotFound)
{
if(range.length > 0)//that is we are checking only the start of the names.
{
[searchResult addObject:str];
}
}
}
}
else
{
//---nothing to search---
isSearchOn = NO;
canSelectRow = NO;
self.ContactTableview.scrollEnabled = YES;
//SearchBar.showsCancelButton = NO;
[TitleBarLabel setText:#"All Contacts"];
}
[ContactTableview reloadData];
}
try with predicates,in below code replace your values.
NSPredicate *p = [NSPredicate predicateWithFormat:#"SELF BEGINSWITH[cd] %#",#"A"];
NSArray *a = [NSArray arrayWithObjects:#"AhfjA ", #"test1", #"Test", #"AntA", nil];
NSArray *b = [a filteredArrayUsingPredicate:p];
NSLog(#"--%#",b);
O/P:-
(
AntA,
AntA
)
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Array: (2007-99 , 2001-96, 2005-93)
Sorted Output should be: (2005-93, 2001-96, 2007-99)
Please help me out.
You need to write a custom comparator to do something like this. In the method below, I get the location of the dash with rangeOfString, then get the substring starting 1 position further into the string, then convert that to an int to do the comparison:
NSMutableArray *arr = [[NSMutableArray alloc] initWithObjects:#"2007-07",#"2005-01",#"2004-09",#"2003-02", nil];
NSArray *sortedArray = [arr sortedArrayUsingComparator: ^(NSString *s1, NSString *s2) {
if ([[s1 substringFromIndex:[s1 rangeOfString:#"-"].location + 1] intValue] > [[s2 substringFromIndex:[s2 rangeOfString:#"-"].location + 1] intValue]) {
return (NSComparisonResult)NSOrderedDescending;
}
if ([[s1 substringFromIndex:[s1 rangeOfString:#"-"].location + 1] intValue] < [[s2 substringFromIndex:[s2 rangeOfString:#"-"].location + 1] intValue]) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}];
NSLog(#"%#",sortedArray);
You can sort this using a custom block (note that I assume that all of your numbers are formatted correctly):
NSArray *rollNumbers = [NSArray arrayWithObjects:#"2007-99", #"2001-96", #"2005-93", nil];
NSArray *sortedRollNumbers = [rollNumbers sortedArrayUsingComparator:^NSComparisonResult(NSString *roll1, NSString *roll2) {
NSArray *roll1Components = [roll1 componentsSeparatedByString:#"-"];
NSArray *roll2Components = [roll2 componentsSeparatedByString:#"-"];
NSNumber *roll1Number = [NSNumber numberWithInt:[[roll1Components objectAtIndex:1] intValue]];
NSNumber *roll2Number = [NSNumber numberWithInt:[[roll2Components objectAtIndex:1] intValue]];
return [roll1Number compare:roll2Number];
}];
NSLog(#"%#", sortedRollNumbers);
Output:
(
"2005-93",
"2001-96",
"2007-99" )
You can sort your array like this :
NSMutableArray *arr = [[NSMutableArray alloc] initWithObjects:#"2007-07",#"2005-01",#"2004-09",#"2003-02", nil];
NSMutableArray *marks = [[NSMutableArray alloc]init];
for (int i = 0; i < arr.count; i++)
{
NSArray *sep = [[arr objectAtIndex:i] componentsSeparatedByString:#"-"];
[marks addObject:[sep objectAtIndex:1]];
}
NSSortDescriptor *sortDesc = [[NSSortDescriptor alloc] initWithKey:#"" ascending:NO];
[marks sortUsingDescriptors:[NSArray arrayWithObject:sortDesc]];
NSMutableArray *sortedFinalArray = [[NSMutableArray alloc]init];
for (int i = 0; i < marks.count; i++)
{
for (int k = 0; k < arr.count; k++)
{
NSRange aRange = [[arr objectAtIndex:i] rangeOfString:[marks objectAtIndex:k]];
if (!(aRange.location == NSNotFound))
{
[sortedFinalArray addObject:[arr objectAtIndex:k]];
}
}
}
In order that you can sort your array, the elements of the array have to be compared pairwise to find out their ordering. Your specific ordering is custom, so you have to write a compare method (e.g. named compare:) by yourself, and then you can use [arr sortUsingSelector:#selector(compare:)]; to sort your array.
Now the compare: method has to be known to the elements of the array, because each element uses it to compare it to another element of the same class. So either you define a new class for your elements that implements the compare method, or you leave them as NSStrings, buth the you have to define a category that implements the compare: method.
The compare: method itself could look like this (pseudo code):
-(NSComparisonResult) compare: (MyString *) myString {
if
(self.the_last_2_characters_interpreted_asNumber <
myString.the_last_2_characters_interpreted_asNumber)
return NSOrderedAscending;
else if
(self.the_last_2_characters_interpreted_asNumber ==
myString.the_last_2_characters_interpreted_asNumber)
return NSOrderedSame;
else
return NSOrderedDescending;
}
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
This is the code I'm trying to finish
-(IBAction)theButtonIsSelected:(id)sender {
NSMutableDictionary *mutDict = [NSMutableDictionary dictionaryWithDictionary:[detailsDataSource objectAtIndex:detailIndex]];
[mutDict setObject:#"Yes" forKey:#"Favorite"];
NSString *nameString = [mutDict valueForKey:#"Name"];
NSArray *allObjects;
allObjects = [[NSArray alloc] initWithContentsOfFile:path];
NSMutableArray *tmpMutArr = [NSMutableArray arrayWithArray:allObjects];
int index;
//I think I just need a little piece right here to set the current allObjectsIndex to match nameString?
[tmpMutArr replaceObjectAtIndex:index withObject:[NSDictionary dictionaryWithDictionary:mutDict]];
allObjects = nil;
allObjects = [[NSArray alloc] initWithArray:tmpMutArr];
[allObjects writeToFile:path atomically:YES];
}
This is my question:
if (what I'm trying to do above can be done) {
How to finish it?
} else {
How to make a function to change the "Favorite" key's value of plist object,
when detailsDataSource not always containing the complete list of objects?
That's why I'm trying to include allObjects and index in this code.
}
EDIT:
Code now look like this:
NSMutableDictionary *mutDict = [NSMutableDictionary dictionaryWithDictionary:[detailsDataSource objectAtIndex:detailIndex]];
[mutDict setObject:#"Yes" forKey:#"Favorite"];
NSString *nameString = [[detailsDataSource objectAtIndex:detailIndex] valueForKey:#"Name"];
NSArray *allObjectsArray = [[NSArray alloc] initWithContentsOfFile:path];
NSMutableArray *tmpMutArr = [NSMutableArray arrayWithArray:allObjectsArray];
if(int i=0;i<[tmpMutArr count];i++)
//Errors ^here and here^
{
if([[tmpMutArr objectAtIndex:i] isKindOfClass:[NSDictionary class]])
{
NSMutableDictionary *tempDict = [tmpMutArr objectAtIndex:i];
if([tempDict valueForKey:#"Name" == [NSString stringWithFormat:#"#%", nameString];) //Is this correct?
{
index = i; //index of dictionary
}
}
}
[tmpMutArr replaceObjectAtIndex:i withObject:[NSDictionary dictionaryWithDictionary:mutDict]];
allObjectsArray = nil;
allObjectsArray = [[NSArray alloc] initWithArray:tmpMutArr];
[allObjectsArray writeToFile:path atomically:YES];
Errors: 1 Expected expression 2 undeclared identifier 'i' how to declare I and fix the other error?
You can get index of dictionary like this:
if(int i=0;i<[tmpMutArr count];i++)
{
if([[tmpMutArr objectAtIndex:i] isKindOfClass:[NSDictionary class]])
{
NSMutableDictionary *tempDict = [tmpMutArr objectAtIndex:i];
if([tempDict objectForKey:#"Favorite")
{
index = i; // here u have your index of dictionary
}
}
}
I have an array which contains strings like frame_10#3x.png , frame_5#3x.png,frame_19#3x.png etc.
So I want to sort this array according to the number after the underscore i.e. the correct sequence will be frame_5#3x.png,frame_10#3x.png,frame_19#3x.png.
I tried to use the following method but no result:
NSInteger firstNumSort(id str1, id str2, void *context) {
int num1 = [str1 integerValue];
int num2 = [str2 integerValue];
if (num1 < num2)
return NSOrderedAscending;
else if (num1 > num2)
return NSOrderedDescending;
return NSOrderedSame;
}
Please suggest how to do this sorting for array.
NSArray *sry_img = [[NSArray alloc] initWithObjects:#"frame_18#3x.png",#"frame_17#3x.png",#"frame_1222#3x.png",#"frame_10#3x.png",#"frame_3#3x.png",#"frame_4#3x.png",#"frame_4#3x.png",#"frame_1#3x.png",#"frame_4#3x.png",#"frame_4#3x.png",nil];
NSArray *sortedStrings = [sry_img sortedArrayUsingSelector:#selector(localizedStandardCompare:)];
NSLog(#"%#",sortedStrings);
Enjy .......
But
localizedStandardCompare:, added in 10.6, should be used whenever file names or other strings are presented in lists and tables where Finder-like sorting is appropriate. The exact behavior of this method may be tweaked in future releases, and will be different under different localizations, so clients should not depend on the exact sorting order of the strings.
you want to do something like:
NSArray *components1 = [str1 componentsSeparatedByString:#"_"];
NSArray *components2 = [str2 componentsSeparatedByString:#"_"];
NSString *number1String = [components1 objectAtIndex:([components1 count] - 1])];
NSString *number2String = [components2 objectAtIndex:([components2 count] - 1])];
return [number1String compare:number2String];
I am not sure if my solution is the best possible approach but it can solve your problem for the time being :) .
1) First I have written a function to get the numbers before # character in your string and then I implemented simple SELECTION SORT algo to sort the array using this functions.
- (NSString*)getSubStringForString:(NSString*)value {
// First we will cut the frame_ string
NSMutableString *trimmedString = [NSMutableString stringWithString:[value substringWithRange:NSMakeRange(6, [value length]-6)]];
// New String to contain the numbers
NSMutableString *newString = [[NSMutableString alloc] init];
for (int i = 0; i < [trimmedString length] ; i++) {
NSString *singleChar = [trimmedString substringWithRange:NSMakeRange(i, 1)];
if (![singleChar isEqualToString:#"#"]) {
[newString appendString:singleChar];
} else {
break;
}
}
return newString;
}
This is the selection Implementation of the algo for sorting. The main logic is in the for loop. You can copy the code in viewDidLoad method to test.
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:#"frame_10#3x.png",#"frame_5#3x.png",
#"frame_3#3x.png", #"frame_19#3x.png",
nil];
NSLog(#"Values before Sort: %#", array);
int iPos;
int iMin;
for (iPos = 0; iPos < [array count]; iPos++)
{
iMin = iPos;
for (int i = iPos+1; i < [array count]; i++)
{
if ([[self getSubStringForString:[array objectAtIndex:i]] intValue] >
[[self getSubStringForString:[array objectAtIndex:iMin]] intValue]) {
iMin = i;
}
}
if ( iMin != iPos )
{
NSString *tempValue = [array objectAtIndex:iPos];
[array replaceObjectAtIndex:iPos withObject:[array objectAtIndex:iMin]];
[array replaceObjectAtIndex:iMin withObject:tempValue];
}
}
NSLog(#"Sorted Values: %#", array);
I hope that it can atleast keep you going. :)
You can try this-
NSString *str1 = [[[[str1 componentsSeparatedByString:#"frame_"] objectAtIndex:1] componentsSeparatedByString:#"#3x.png"] objectAtIndex:0];
int num1 = [str1 integerValue];
i'm using uitextview for searching the contact details from address book. i.e., like uisearchbar search the contact details while text edit change in uitextview.
i'm using uitextview if i tap 'a', the list of the contacts from address book will be display in table view
please give me the solution
Finally I got the solution simple coding here it is
//viewDidLoad
NSMutableArray *personArray = [[NSMutableArray alloc] init];
ABRecordRef personRef;
for (int i = 0; i < CFArrayGetCount(allPeople); i++)
{
personRef = (ABRecordID*)CFArrayGetValueAtIndex(allPeople, i);
ABRecordRef person = ABAddressBookGetPersonWithRecordID(addressBook, ABRecordGetRecordID(personRef));
#try
{
if (ABRecordCopyValue(person, kABPersonBirthdayProperty))
[personArray addObject: (id)personRef];
}
#catch (NSException * e)
{
}
#finally
{
}
NSString *FirstName = [[[NSString stringWithString:(NSString *)ABRecordCopyValue(personRef, kABPersonFirstNameProperty)]stringByAppendingString:#" "]stringByAppendingString:(NSString *)ABRecordCopyValue(personRef, kABPersonLastNameProperty)];
[arr addObject:FirstName];
}
[arr3 addObjectsFromArray:arr];
}
//textviewdidchange
[arr3 removeAllObjects];
NSInteger counter = 0;
for(NSString *name in arr)
{
NSRange r = [name rangeOfString:txtView.text options:NSCaseInsensitiveSearch];
if(r.location != NSNotFound)
{
[arr3 addObject:name];
}
counter++;
}
[table reloadData];
Thanks for your help