sorting UITableview cells by creation order swift - swift

Right now I have a tableview that loads data from coredata and I would like to know how it is possible to order these cells by their order of creation. I'd like for the user to be able to see the most recent cells created at the top of the tableview.
Thanks.

You can:
Add a sort descriptor to your request:
//Entity
NSString *entityName = #"Days";
//Fetch Request
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:entityName];
//Sort
request.sortDescriptors = #[[NSSortDescriptor sortDescriptorWithKey:#"created_at" ascending:YES]];
Sort the array of results:
NSSortDescriptor * sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"DatePropertyName" ascending:YES];
NSArray *descriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray = [myArray sortedArrayUsingDescriptors:descriptors];

Related

iPhone:Fetch data from core data sorted according to index

Fetch data from core data sorted according to index
In core data entity i have a field index which have index (1,2,3,4,5,6,7,......)
I want to fetch data from core data according to that index but i am unable to do that
I am not able to properly set sortdescriptor
Anyone Please help with some code snippet
To tell the fetch request to sort your data...
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:#"myEntity"];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"index" ascending:YES];
fetchRequest.sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
Now when you fetch, the data will be sorted according to the index field.
/*!
#param <NSManagedObject> array
#return <NSManagedObject> sortedarray
*/
+ (NSArray *) sortManagedObjectArrayByObjectID:(NSArray *) array {
NSArray *compareResult = [array sortedArrayUsingComparator:^NSComparisonResult(NSManagedObject *obj1, NSManagedObject *obj2) {
NSString *s = [obj1.objectID.URIRepresentation lastPathComponent];
NSString *r = [obj2.objectID.URIRepresentation lastPathComponent];
return [s compare:r];
}];
return compareResult;
}

NSFetchedResultsController setLimit for each Section

How would you go about setting the limit of each section in a tableview controlled by a NSFetchedResultsController? For example: I have a bunch of shows that each have start dates and play on different stages. I want to be able to show only who's up next on each stage. So I need not a limit on the whole request, but a limit on each section.
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:#"Event"];
NSMutableArray *predicates = [NSMutableArray array];
[predicates addObject:[NSPredicate predicateWithFormat:#"startDate > %#", [NSDate date]]];
request.predicate = [NSCompoundPredicate andPredicateWithSubpredicates:predicates];
NSSortDescriptor *stageSort = [[NSSortDescriptor alloc] initWithKey:#"stage.id" ascending:YES];
NSSortDescriptor *dateSort = [[NSSortDescriptor alloc] initWithKey:#"startDate" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:stageSort, dateSort, nil];
[request setSortDescriptors:sortDescriptors];
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
managedObjectContext:self.managedObjectContext
sectionNameKeyPath:#"stage.id"
cacheName:nil];
This kind of works if I limit the it in the tableview delegate methods but often crashes when the fetch changes and it trys to update the table. I think it's because there are a lot more objects in the NSFetchedResultsController than are showing and the animation of changing these breaks it.
How would I go about setting a more effective limit per section? I only want the first result per section.
In general, I think your approach is feasible.
Just fix your table update routines. Before inserting a row, check your logic if it should be done, and if not, skip the insert.

counting issue with NS Managed object and NS ARRAY

I am trying to count the number of objects in my core data , so that I can tell how many rows are needed my table view controller, but I am stuck with counting of NS ARRAY, here is the code
NSFetchRequest *request = [[NSFetchRequest alloc] init];
request.entity = [NSEntityDescription entityForName:#"Data" inManagedObjectContext:context];
NSSortDescriptor *sortDescriptor =
[[NSSortDescriptor alloc] initWithKey:#"date"
ascending:YES
selector:#selector(localizedCaseInsensitiveCompare:)];
request.sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSError *error = nil;
NSArray *temp=[context executeFetchRequest:request error:&error];
I am doing it in Data class(sub class of nsmanged object), the issue is when I reach
NSLog(#"%#",[temp count]);
I get ‘Program received signal:”EXC_BAD_ACCESS”’
I dnt get what is wrong, I am putting my data into a ns array and than trying to count them . help in this regard will be greatly appreciated .
[temp count] return a number , not a string
so you need
NSLog(#"%u",[temp count]);
look at this

Sorting Array of Custom Class Objects

I am facing problem that is of sorting. The scenario is explained as: i have a class (Suppose of person) and it has suppose 4 attributes (firstName, lastName, Address, salary) i am creating its object and making a collection of all attributes and putting this object in a NSMutableArray and so on. So at every index of array i have one object (i.e collection of 4 attributes). Now i want to sort that array on the basis of salary can anyone help me out regarding this problem, will be thankful.,
See the documentation for NSArray. It has several sorting methods. Search for the word "sort" and you'll find 'em. (You'll want either the block based or function based API).
use this
NSSortDescriptor *sorter = [[[NSSortDescriptor alloc] initWithKey:#"salary" ascending:YES] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject: sorter];
[yorArrary sortUsingDescriptors:sortDescriptors];
Either you implement a compare-method for your object:
- (NSComparisonResult)compare:(Person *)otherObject {
return [self.birthDate compare:otherObject.birthDate];
}
NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingSelector:#selector(compare:)];
or usually even better: (The default sorting selector of NSSortDescriptor is compare:)
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:#"birthDate"
ascending:YES] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingDescriptors:sortDescriptors];

How can I sort an NSMutableArray alphabetically?

I want to sort an NSMutableArray alphabetically.
You can do this to sort NSMutableArray:
[yourArray sortUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
The other answers provided here mention using #selector(localizedCaseInsensitiveCompare:)
This works great for an array of NSString, however the OP commented that the array contains objects and that sorting should be done according to object.name property.
In this case you should do this:
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:#"name" ascending:YES];
[yourArray sortUsingDescriptors:[NSArray arrayWithObject:sort]];
Your objects will be sorted according to the name property of those objects.
NSSortDescriptor *valueDescriptor = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:YES]; // Describe the Key value using which you want to sort.
NSArray * descriptors = [NSArray arrayWithObject:valueDescriptor]; // Add the value of the descriptor to array.
sortedArrayWithName = [yourDataArray sortedArrayUsingDescriptors:descriptors]; // Now Sort the Array using descriptor.
Here you will get the sorted array list.
In the simplest scenarios, if you had an array of strings:
NSArray* data = #[#"Grapes", #"Apples", #"Oranges"];
And you wanted to sort it, you'd simply pass in nil for the key of the descriptor, and call the method i mentioned above:
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES];
data = [data sortedArrayUsingDescriptors:#[descriptor]];
The output would look like this:
Apples, Grapes, Oranges
For more details check this
Use the NSSortDescriptor class and rest you will get every thing here
NSSortDescriptor * sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"Name_your_key_value" ascending:YES];
NSArray * sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray * sortedArray;
sortedArray = [Your_array sortedArrayUsingDescriptors:sortDescriptors];
Maybe this can help you:
[myNSMutableArray sortUsingDescriptors:#[[NSSortDescriptor sortDescriptorWithKey:#"firstName" ascending:YES],[NSSortDescriptor sortDescriptorWithKey:#"lastName" ascending:YES]]];
All is acording to NSSortDescriptor...