insertNewObjectForEntityForName at first position in the table not last - ios

How to insert the record with coredata at first position in table? currently if i add insertNewObjectForEntityForName it adds record to last.

Well, as far as i know this is not possible. However one thing you could do is manipulate how the objects are retrieved from the DB. For example, for such requirements it is often useful to have an NSDate property in your model class. While inserting objects into the DB, pass [NSDate date] for this property. And while pulling out objects from the DB, write a sorting algorithm which returns the records sorted by the Date of insertion
In your model class' header file
Header.h
//Declare this property
NSDate *dateOfInsertion
//This method returns objects sorted by DateOf Insertion
- (NSArray*)arraySortedByDateOfInsertion {
NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:#"dateOfInsertion" ascending:NO];
return [self sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]];
}
Hope this helps

You cannot decide where to add element in the table. But you use array for this . You can add the element at the top of the array so it will appeared as a first row in the table :
- (void)insertObject:(id)anObject atIndex:(NSUInteger)index

Related

Fetching latest value from core data and assigning it to a label. Swift

I've only been coding for 2 weeks now and I am trying to build a 'weights logger app'. I am saving the weights under the entity - "Weights" with attributes for "benchPress", "deadLift" etc.
I figured out how to save values. So when the user clicks save, it saves the recorded value to the array.
But I don't know how to fetch the 'latest' value and set it equal to a UILabel.
Image showing the entity
The code I have so far to fetch the result
Any help would really be appreciated. I've been stuck on this for a while now. Thanks!
Core Data doesn't have any concept of "latest". It doesn't track when new data has been saved. If you need something like the most recent entry, you need to add your own field-- a date, or an integer index, or something that would indicate the correct instance to fetch.
If you added a date field named date, you'd get the entry with the most recent date using a fetch request something like this:
NSFetchRequest *fetch = [NSFetchRequest fetchRequestWithEntityName:#"Weights"];
NSSortDescriptor *dateSort = [NSSortDescriptor sortDescriptorWithKey:#"date" ascending:NO];
fetch.sortDescriptors = #[ dateSort ];
fetch.fetchLimit = 1;
The result would be an array containing at most one object, which would have the most recently saved date.

Multiple sort on Array for UITableView

I have an array of categories returned from a parse.com query (sorted ascending) that are listed in a TableView.
I want to place a category called "Everything" at the top of the list and then sort the rest of the list ASC. I'm thinking I should use NSDescriptor, NSComparator or NSPredicate but wanted to get some feedback on the best route.
Another angle I thought might work is to extract "Everything" out of the array and put it in a string and then use 2 custom cells and put "Everything" on top.
Any advice on which option would be best? Or is there another route I missed?
I solved this by copying the results Array into a mutable Array and then sorted the Array.
NSMutableArray *sort = [[NSMutableArray alloc] initWithArray:self.objects];
id tmp=[sort objectAtIndex:6];
[sort removeObjectAtIndex:6];
[sort insertObject:tmp atIndex:0];

"IN" NSPredicate where the search is made within an array of objects

I have an array called deletedDepartments which contains NSObjects called DeletedObject. A DeletedObject only has a field called deletedID. This array is generated from a mapping with RestKit.
Now, I want to search within CoreDate for Department objects where their id is within the deletedDepartments array.
If I do
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:#"id IN %#", deletedDepartments ]];
This won't work because deletedDepartments is not a NSArray made of NSNumber, but of NSObject which contains the NSNumber I want to compare. How can I achieve such thing without creating another array made from iterating over the deletedDepartments and selecting only the deletedID?
Change your predicate to the following :
[NSPredicate predicateWithFormat:#"deletedID IN %#", [deletedDepartments valueForKey:#"deletedID"]]
This will create an array of your deletedId's, and evaluate each object using the deletedId property. While, yes, this does internally iterate over the array to create a new one, that's the best you can do unless the NSObjects in deletedDepartments are of the same class as the model objects that your are fetching.

iOS NSFetchedResultsController: sort sections by >=2 properties

I use NSFetchedResultsController to fetch from database with Core Data. And I have an Entity with 2 properties, prop1 and prop2 of NSString.
How would I sort sections not only by one of the properties but both?
Now it is:
Title1ForProp1/Title2ForProp2 (prop1==1 prop2==2)
Title1ForProp1/Title1ForProp2 (prop1==1 prop2==1)
Title2ForProp1/Title1ForProp2 (prop1==2 prop2==1)
I need:
Title1ForProp1/Title1ForProp2 (prop1==1 prop2==1)
Title1ForProp1/Title2ForProp2 (prop1==1 prop2==2)
Title2ForProp1/Title1ForProp2 (prop1==2 prop2==1)
When you create the fetch request for the NSFC you create the sort descriptor and give the request an array.
You can put as many sort descriptors in the array as you like.
Just create a sort descriptor for each field you want to sort by.
I can remember which order you have to put them into the array though.
OK, so code wise...
NSSortDescriptor *sd1 = [[NSSortDescriptor alloc] initWithKey:#"prop1" ascending:YES];
NSSortDescriptor *sd2 = [[NSSortDescriptor alloc] initWithKey:#"prop2" ascending:YES];
[fetchRequest setSortDescriptors:#[sd1, sd2]];
This is all you have to do.
The NSFC will only split them into sections if you give it a sectionNameKeyPath. If you don't want any sections then make the sectionNameKeyPath nil.
Fogmeister's sort descriptors array is appropriate (sort on prop1 then prop2) but if you provide prop1 in your sectionNameKeyPath your sections would be broken up only by prop1. Within each section, the items would be sorted by both prop1 and prop2.
If this is not what you want and you need to additionally group your results into sections by both prop1 and prop2, you probably want to create a transient property that concatenates both prop1 and prop2 and provide that transient property as your sectionNameKeyPath. This provides not just the title for the section but also determines how results are grouped into sections.
Take a look at this question for how you might create a transient property for your section names:
NSFetchedResultsController with sections created by first letter of a string

Sort multiple arrays

Here is my situation:
I manipulate 6 NSMutableArrays. One of them has NSDates objects in it, the other ones have NSNumbers. When I populate them, I use addObject: for each of them, so index 0 of each array contains all the values I want for my date at index 0 in the dates array.
I want to make sure that the arrays are all sorted according to the dates array (order by date, ascending), meaning that during the sorting, if row 5 of the dates array is moved to row 1, it has to be applied to all the other arrays as well.
I was previously using CoreData, but I must not use it anymore (please don't ask why, this is off-topic ;) ). In CoreData, I could use an NSSortDescriptor, but I have no idea on how to do it with multiple NSArrays...
As always, hints/answers/solutions are always appreciated :)
This is a common problem. Use the following approach.
Encapsulate your six arrays into an object - every instance will have six properties.
Implement compare: method on this object, using [NSDate compare:] (this step can be skipped but it's cleaner this way).
Now you have only one array - sort it using the method from step 2.
I think the better solution for you to have NSArray of NSDictionary objects.
NSArray *allValues = [[NSArray alloc] init];
NSDictionary *dict = #{"Date" : [NSDate date], #"Key1" : #"Value1", #"Key2" : #"Value2"};
Then you can sort this array with sortDescriptor without any problems.
And then you can also use Comparator or Sort Desriptor as you wish.
Wrap all your items that you are storing in an array into a single object. Each one of your previous 6 arrays will be a property.
Inside that object you can implement
- (NSComparisonResult)compare:(YourClass *)otherObject {
return [self.date compare:otherObject.date];
}
You can now sort the array and they will sort by date.

Resources