views:

195

answers:

2

I'm using core data and fetching the results successfully. I've few questions regarding core data 1. When I add a record, will it be added at the end or at the start of entity. 2. I'm using following code to fetch the data. Array is being populated with all the records. But they are not in the same order as I entered records into entity. why? on what basis default sorting is used?

    NSFetchRequest* allLatest = [[NSFetchRequest alloc] init];
[allLatest setEntity:[NSEntityDescription entityForName:@"Latest" inManagedObjectContext:[self managedObjectContext]]];

NSError* error = nil;
NSArray* records = [managedObjectContext executeFetchRequest:allLatest error:&error];
[allLatest release];

3. The way that I enter the records, 1,2,3,4......... after some time, I want to delete the records that I entered first(i mean oldest data). Something like delete oldest two records. How to do it?

+3  A: 

Ordering is not guaranteed in any way. If you care about order, you need to include an attribute in your entity (for example, call it "sequenceNumber") and use that in a sort descriptor with your NSFetchRequest.

David Gelhar
A: 

A sort on the array you have looks like this:

NSSortDescriptor *descriptor = [[[NSSortDescriptor alloc] initWithKey:@"SortKey" ascending:YES] autorelease];
NSArray *sortedList = [records sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor, nil]];

The initWithKey: argument is the property you would like to sort on. If you have multiple keys to sort on, they can be added to the sortedArrayUsingDescriptors: argument as a list. The list will be sorted by the first descriptor, then each group by the next descriptors.

-dan

Daniel Blezek
I don't want to sort. I want the records in the order that I inserted into entity.
Satyam svv
If I add some "Date" property to the entity and then can I fetch the records sorted directly from core date. Or else, can I delete the records keeping only latest one week data?
Satyam svv