Reputation: 499
I am haing a Simple Iphone based apllication.In that Application coredata is is used for storing data.
I have two fields. one Field is Mesage and other field is date.I want to take the mesage which is sent within last 10 days. I know to this code is used for that..but how to implement this?????
sortedArray = [unsortedArray sortedArrayUsingFunction:sortByStringDate context:NULL]
how to write a query and how to implement this...Anybody help me to implement this.....Advance thanks
Upvotes: 0
Views: 3148
Reputation: 13675
Do something like this:
// Calculate NSDate for 10 days ago
NSDate *now = [NSDate date]; // get current date
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
dateComponents.day = -10;
NSDate *tenDaysAgo = [calendar dateByAddingComponents:dateComponents toDate:now options:0];
[dateComponents release];
// Create NSFetchRequest
NSFetchRequest *req = [[NSFetchRequest alloc] initWithEntityName:@"MyEntity"];
req.predicate = [NSPredicate predicateWithFormat:@"date >= %@", tenDaysAgo];
// Optionally add a sort descriptor too
// Execute fetch request
NSError *error = nil;
NSArray *results = [managedObjectContext executeFetchRequest:req error:&error];
If this doesn't make sense to you then read about NSFetchRequests and Predicates in the Core Data Programming Guide.
Upvotes: 2
Reputation: 17877
If you want to sort array by property date
of objects in that array you can write such call:
sortedArray = [unsortedArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"date" ascending:YES]]];
Upvotes: 3