get IndexPath in a Sorted Array - ios

I am getting values which are sorted from a plist and displaying them in a tableview. I am providing the capability of entering a custom category which will be written to plist. But I want that to be Inserted in the sorted alphabetical order. Can someone suggest me how to get the indexpath of the row where it has to be inserted. I have used the following code where the custom entry will be inserted at the 0 location
NSInteger section = 0;
NSInteger row = 0;
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
NSDictionary *categoryDictionary = [NSMutableDictionary dictionary];
[categoryDictionary setValue:newCategoryName forKey:#"name" ];
[categoryDictionary setValue:#"custom.png" forKey:#"image"];
[[self categoriesArray]insertObject:categoryDictionary atIndex:row];
[[self categoriesArray] writeToFile:[self dataFilePath] atomically:YES];
NSArray *indexPathsToInsert = [NSArray arrayWithObject:indexPath];
[[self tableView]insertRowsAtIndexPaths:indexPathsToInsert withRowAnimation:UITableViewRowAnimationRight];
[self.categoriesArray writeToFile:[self dataFilePath] atomically:YES];

Try
NSMutableDictionary *categoryDictionary = [NSMutableDictionary dictionary];
[categoryDictionary setObject:newCategoryName forKey:#"name" ];
[categoryDictionary setObject:#"custom.png" forKey:#"image"];
//Add new category to array
[self.categoriesArray addObject:categoryDictionary];
//Sort Array
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:#"name" ascending:YES];
[self.categoriesArray sortUsingDescriptors:#[sortDescriptor]];
//Write array to plist
[self.categoriesArray writeToFile:[self dataFilePath] atomically:YES];
NSInteger section = 0;
//Get the index of saved Category item
NSInteger row = [self.categoriesArray indexOfObject:categoryDictionary];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
[self.tableView insertRowsAtIndexPaths:#[indexPath]
withRowAnimation:UITableViewRowAnimationRight];

In your table you will get section and row using following
NSInteger section = indexPath.section;
NSInteger row = indexPath.row;

if you have an array of sortable items, you can use this code snippet as help:
NSArray *sortedArray = #[#"a" , #"b", #"d", #"c", #"f"];
sortedArray = [sortedArray sortedArrayUsingSelector:#selector(caseInsensitiveCompare:)];
NSLog(#"%#", sortedArray);
int c = [sortedArray indexOfObject:#"c"];
NSLog(#"%d", c);
Logs ->
(
a,
b,
c,
d,
f
)
2
so you first insert your object in the "toSort" array and then get the index of it ;)

Related

Sorting many labels in a tableView

I have a custom UITableviewCell which contains a few UILabels on them. The data is received from web services and I'd like to sort them based on one of the UILabels. The data received is stored in an array. How can I sort them?
Thanks! :)
Code written to add data to the cells from a BO:
cells.head.text = [[self.messageStore objectAtIndex:indexPath.section] subject];
cells.subhead.text = [[self.messageStore objectAtIndex:indexPath.section] messageli];
cells.signature.text=[AppConstants getUsername];
cells.viewCount.text = [NSString stringWithFormat:#"%# Views",[[self.messageStore objectAtIndex:indexPath.section] viewsCount]];
cells.interested.text= [[self.messageStore objectAtIndex:indexPath.section] interestedCount];
cells.date.text = [[self.messageStore objectAtIndex:indexPath.section] creationDate];
[cells.image1 sd_setImageWithURL:[NSURL URLWithString:[[self.messageStore objectAtIndex:indexPath.section] imageURL]] placeholderImage:[UIImage imageNamed:#"no_photo.png"]];
cells.editZButton.hidden = NO;
cells.editZButton.tintColor = [UIColor whiteColor];
cells.deleteZButton.hidden = NO;
cells.amount.text = [NSString stringWithFormat:#"$ %#",[[self.messageStore objectAtIndex:indexPath.section] priceAmount]]; cells.editZButton.tag = indexPath.section;
cells.deleteZButton.tag = indexPath.section;
[cells.editZButton addTarget:self action:#selector(editButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
[cells.deleteZButton addTarget:self action:#selector(deleteButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
You can sort the data using the predicate
NSPredicate *predicate=[NSPredicate predicateWithFormat:#"Your_Key ==%#",Your_Value_For_Key];
NSArray *array=[Your_Array_Of_Data filteredArrayUsingPredicate:predicate];
Since you didn't gave us the exact array to be sorted, I'm assuming its just a simple NSArray of strings.
You can use NSSortDescriptor to sort NSArray as below
NSArray *arr = [[NSArray alloc] initWithObjects:#"Sam", #"John", #"Andrew", nil];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:#"self" ascending:NO];
NSArray *sortedArray = [arr sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
Then reload your tableview with the "sortedArray".
Below one is generic method, you can try.
- (NSMutableArray*)sortArray:(NSMutableArray*)dataArray filterKeyName:(NSString*)KeyName ascending:(BOOL)isAscending{
NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:KeyName ascending:isAscending];
[dataArray sortUsingDescriptors:[NSArray arrayWithObject:sorter]];
return dataArray; // Sorted data array..
}

Iterating Through NSIndexSet

If you have an NSArray object named anArray and an NSIndexSet object named anIndexSet, you can iterate forward through an index set as shown in below.
Excerpt, Apple Documents:
NSArray *anArray = [NSArray array];
NSIndexSet *anIndexSet = [NSIndexSet indexSetWithIndex:3];
NSUInteger index = [anIndexSet firstIndex];
while(index != NSNotFound) {
NSLog(#" %#",[anArray objectAtIndex:index]);
index = [anIndexSet indexGreaterThanIndex:index];
}
Why terminating NSRangeException in the above scenario?
I think this example describes the situation better. Also, not used an empty array as you say. Thanks so much rmaddy!!!
NSMutableArray *mutableArray = [NSMutableArray arrayWithObjects:#"K",#"G",#"G",#"E",#"R",#"G",#"E",#"G",#"G",#"M", nil];
NSIndexSet *anIndexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [mutableArray count])];
NSUInteger index = [anIndexSet lastIndex];
while (index != NSNotFound) {
if ([[mutableArray objectAtIndex:index] isEqualToString:#"G"]) {
[mutableArray removeObjectAtIndex:index];
}
index = [anIndexSet indexLessThanIndex:index];
}
NSLog(#" %#", mutableArray);

How can I select elements from an NSArray according to array of NSIndexPaths

Is there a fast way to get all elements at indexes from an array returned from a UITableView (NSArray of NSIndexPaths).
For instance:
[self.dataSourceArray selectItemsAt:[self.tableView indexPathsForSelectedItems]]
There is no built-in method, but you can simply loop over the selected rows
(assuming that there is only one section) and add the corresponding elements
to a mutable array:
NSMutableArray *selectedObjects = [NSMutableArray array];
for (NSIndexPath *indexPath in [self.tableView indexPathsForSelectedRows]) {
[selectedObjects addObject:self.dataSourceArray[indexPath.row]];
}
word you are looking for is Lambda
there is two methots for that
you can look for it in link
Does Objective-C have List Lambda Query like C#?
it should look like this
NSPredicate *p = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
for(NSIndexPath i in [self.tableView indexPathsForSelectedItems]){
if(i.row == evaluatedObject.row){
return YES;
}
}
return NO;
}];
NSArray *result = [self.dataSourceArray filteredArrayUsingPredicate:p];
Use objectsAtIndexes: method of NSArray.
NSMutableIndexSet *mutableIndexSet = [[NSMutableIndexSet alloc] init];
// Add all indexes to NSMutableIndexSet
for (int i = 0; i < [self.tableView indexPathsForSelectedRows].count; i++) {
[mutableIndexSet addIndex: ((NSIndexPath *) [self.tableView indexPathsForSelectedRows][i]).row];
}
[self.dataSourceArray objectsAtIndexes:mutableIndexSet];

searching NSString from NSMutableArray and Adding in UiTableView

i have contains list of countries. such as
countries_list = [NSMutableArray arrayWithObjects:#"Afghanistan",#"Albania",
#"Bolivia",#"Bulgaria",#"China", #"Estonia",#"France",#"Finland",
#"Greenland",#"Iceland",#"Japan", nil];
from this array i need to search such as Albania in sorted list all countries come which start with the alphabet Letter A and then sort Al so on and then i have to add these values in the uitableview..
i just need searching help me if any one can. thanks
NSMutableArray* containsAnother = [NSMutableArray array];
NSMutableArray* doesntAnother = [NSMutableArray array];
for (NSString* item in inputArray)
{
if ([item rangeOfString:#"Finland"].location != NSNotFound){
[containsAnother addObject:item];
NSLog(#"country is found..%#",containsAnother);
}else{
}
[doesntContainAnother addObject:item];
NSLog(#"country is not found..%#",doesntContainAnother);
}
NSLog(#"array is found..%#",containsAnother);
You can use NSPredicate class for this like this :-
NSMutableArray * array = [NSMutableArray array];
// Loop to fetch Team Names and store in NSMutableArray named array
for (NSDictionary *data in mySortedArray) {
NSString *TEAMNAME = #"TeamName";
NSString *countryName = #"Australia";
NSDictionary sortDictionary = [NSDictionary dictionaryWithObjectsAndKeys:countryName,TEAMNAME,nil];
[array addObject:sortDictionary];
}
NSSortDescriptor * ratingDescriptor =[[[NSSortDescriptor alloc] initWithKey:TEAMNAME ascending:YES] autorelease];
NSArray * descriptors = [NSArray arrayWithObjects:ratingDescriptor, nil];
mySortedArray = (NSMutableArray *)[array sortedArrayUsingDescriptors:descriptors];
And it is done. Hope it helps :)
try using NSPredicate predicateWithFormat: method
countries_list = [NSMutableArray arrayWithObjects:#"Afghanistan",#"Albania",#"Bolivia",#"Bulgaria",#"China", #"Estonia",#"France",#"Finland", #"Greenland",#"Iceland",#"Japan", nil];
NSPredicate *predicte = [NSPredicate predicateWithFormat:
#"Self beginswith[c] %#", #"Albania"];
NSArray *filteredArray = [countries_list filteredArrayUsingPredicate:predicte];
NSLog([filteredArray description]);

how to change order of NSMutable array in same way another mutable arrays get changed

I have three arrays. They are name, birthdates and remaining days like below:
name birthdate remaining
"Abhi Shah", "01/14", 300
"Akash Parikh", "12/09/1989", 264
"Anand Kapadiya", "12/01", 256
"Annabella Faith Perez", "03/02", 347
"Aysu Can", "04/14/1992", 25
"Chirag Pandya" "10/07/1987" 201
I want to rearrange the remaining days array into ascending order,
but at the same time name and birthdate should also get reordered in the same way.
See this example below:
name birthdate remaining
"Aysu Can", "04/14/1992", 25
"Chirag Pandya" "10/07/1987" 201
"etc..."
use NSMutableDictionary to store data to NSMutableArray
NSMutableArray *array=[[NSMutableArray alloc]init];
for (int i=0; i<totalRows; i++)
{
NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
[dic setValue:[array_1 objectAtIndex:i] forKey:#"names"];
[dic setValue:[array_2 objectAtIndex:i] forKey:#"birthdate "];
[dic setValue:[array_3 objectAtIndex:i] forKey:#"remanning"];
[array addObject:dic];
[dic release];
}
here after you arrange name array,use search option to use name not use index and
use NSPredicate search data in NSMutableArray
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"names matches[cd] %#", name];
NSArray *result = [array filteredArrayUsingPredicate:predicate];
NSMutableDictionary *dict = [[[result objectAtIndex:0] mutableCopy] autorelease];
NSLog(#"%#",dict);// result
self.arrayForRows = [[NSMutableArray alloc]init];
NSMutableArray *arrayForNames = [[NSMutableArray alloc]initWithObjects:#"Abhi Shah",#"Akash",#"Nagavendra",#"Ramana",#"Simhachalam", nil];
NSMutableArray *arrayForBirthDates = [[NSMutableArray alloc]initWithObjects:#"01/14/94",#"01/14",#"11/07/87",#"12/07/89",#"23/08/91", nil];
NSMutableArray *arrayForRemaining = [[NSMutableArray alloc]initWithObjects:#"200",#"320",#"32",#"450",#"14", nil];
for (int i=0; i<arrayForBirthDates.count; i++)
{
NSMutableDictionary *tempDicts = [[NSMutableDictionary alloc]init];
[tempDicts setObject:[arrayForNames objectAtIndex:i] forKey:#"names"];
[tempDicts setObject:[arrayForBirthDates objectAtIndex:i] forKey:#"birth"];
[tempDicts setObject:[NSNumber numberWithInt:[[arrayForRemaining objectAtIndex:i] intValue]] forKey:#"remaining"];
[self.arrayForRows addObject:tempDicts];
}
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"remaining" ascending:YES];
[self.arrayForRows sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
Use this in tableView listing
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.arrayForRows count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifer = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifer];
if (cell == nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifer];
}
cell.textLabel.text = [[self.arrayForRows objectAtIndex:indexPath.row] valueForKey:#"names"];
return cell;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
once try like this it'l help you,
NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];
[dict setObject:#"rahul" forKey:#"name"];
[dict setObject:#"10" forKey:#"value"];
NSMutableDictionary *dict1=[[NSMutableDictionary alloc]init];
[dict1 setObject:#"ttt" forKey:#"name"];
[dict1 setObject:#"6" forKey:#"value"];
NSMutableArray *ar=[[NSMutableArray alloc]init];
[ar addObject:dict];
[ar addObject:dict1];
NSSortDescriptor *Sorter = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:NO];
[ar sortUsingDescriptors:[NSArray arrayWithObject:Sorter]];
NSLog(#"---%#",ar);
Put each row into a dictionary, and out those dictionaries into an array. Then sort your away using a predicate or sort block. If you want an array containing just the sorted names for example, you could use [ array valueForKeyPath:#"name" ]
Array looks like:
[
{ #"name" : ...,
#"birthdate" : ...birthdate...,
#"remaining" : ...days remaining... } ,
{...},
{...}
]
such as your MutableArray is a Dictionarys array , you can use sortUsingComparator
to sort the array
[array sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
int a = [(NSNumber *)[(NSDictionary *)obj1 objectiveForKey: #"remanning"] intValue];
int b = [(NSNumber *)[(NSDictionary *)obj2 objectiveForKey: #"remanning"] intValue];
if (a < b) {
return NSOrderedAscending;
}
else if(a == b)
{
return NSOrderedSame;
}
return NSOrderedDescending;
}];
For example , I have a test :
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:#(30),#(20),#(5),#(100), nil];
[array sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
int a = [(NSNumber *)obj1 intValue];
int b = [(NSNumber *)obj2 intValue];
if (a < b) {
return NSOrderedAscending;
}
else if(a == b)
{
return NSOrderedSame;
}
return NSOrderedDescending;
}];
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(#"%# , %d",obj,idx);
}];
then the output is :

Resources