NSPredicate compare dates in CoreData - iphone

I have a managed object with two dates: dateOne and dateTwo and I want to retrieve the dates where dateTwo is older than dateOne.
Right now I am using the following predicate to fetch the objects:
NSArray *objects = nil;
NSFetchRequest *request = [[NSFetchRequest alloc] init];
request.entity = [NSEntityDescription entityForName:#"Object" inManagedObjectContext:context];
request.predicate = [NSPredicate predicateWithFormat:#"dateOne > dateTwo", #""];
objects = [context executeFetchRequest:request error:nil];
[request release];
Sometimes it works, but other times the objects fetched have a dateTwo that is more recent than dateOne. Is there a better way to do something like this?
Thanks!

Perhaps you could add a BOOL property "dateTwoIsOlder" to the entity, then just fetch objects that adhere to that?

Why not just create a fetch request from core data and not do it programmatically?

Related

Fetching strings (or other variables) from a CoreData fetch request?

I have Core Data setup in my app and need to fetch a bunch of items and then access the properties I choose of those fetched items. I am able to successfully fetch a bunch of results like this:
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"TableInfo" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
NSError *error = nil;
NSArray *result = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
This gives me an array with my results, great. Now from this how can I for example get the 'name' property from these results? In this specific circumstance I want to load an array with all of the fetched results 'name' strings.
If I read your question correctly, you are able to fetch your NSManagedObjects without difficulty, but would like to derive another NSArray with name properties on those managed objects?
Then you can use the valueForKeyPath on the NSArray (extending your original code):
NSArray *names = [result valueForKeyPath:#"name"];
You can use the key-value:
for (NSManagedObject *fetchedResult in result) {
NSLog(#"name = %#", [fetchedResult valueForKey:#"name"]);
}
or if you created your custom NSManagedObject:
for (EntityObject *fetchedResult in result) {
NSLog(#"name = %#", [fetchedResult name]);
}

How to sum on a calculated property?

I'm sure I'm guilty of trying to apply SQL logic to Core Data, but even after reading the Apple docs I'm still not sure of the correct approach.
What would be the best strategy for summing the difference of two date properties in a Core Data entity? I have a "numHours" calculated property on the "appt" class but not in the xcdatamodel. The code below fails with a "keypath not found in entity" error. Many thanks for any advice.
from appt class
- (float)numHours {
float hours = ([self.endTime timeIntervalSinceDate:self.startTime] - [self.durationOfBreak intValue]) / 3600.00;
return hours;
}
attempt at fetching sum of "numHours" property
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"appt" inManagedObjectContext:self.managedObjectContext];
[request setEntity:entity];
NSPredicate *datePredicate = [NSPredicate predicateWithFormat:#"date >= %# && date < %#", self.startDate, self.endDate];
[request setPredicate:datePredicate];
[request setResultType:NSDictionaryResultType];
NSExpression *numHoursPath = [NSExpression expressionForKeyPath:#"numHours"];
NSExpression *hoursSum = [NSExpression expressionForFunction:#"sum:"
arguments:[NSArray arrayWithObject:numHoursPath]];
NSExpressionDescription *debitExpressionDescription = [[NSExpressionDescription alloc] init];
[debitExpressionDescription setName:#"totalhours"];
[debitExpressionDescription setExpression:hoursSum];
[debitExpressionDescription setExpressionResultType:NSDecimalAttributeType];
[request setPropertiesToFetch:[NSArray arrayWithObject:debitExpressionDescription]];
[debitExpressionDescription release];
NSError *error = nil;
NSArray *results = [managedObjectContext executeFetchRequest:request error:&error];
Jeffery,
You cannot fetch based upon an attribute that isn't actually in the model. The error message, "keypath not found in entity," plainly says this. You can confirm this for yourself by browsing the SQLite DB and you'll see there is no attribute for the SQL to query. Hence, your fetch request must fail. NSExpression *numHoursPath is a valid expression. It can be applied to collections after you've fetched them. You just cannot use them in a fetch request.
Andrew

fetching objects from core data not in a set

I'm trying to fetch objects from core data that are not in a given set, but I haven't been able to get it to work.
For instance, suppose that we have a core data entity named User, which has a few attributes such as userName, familyName, givenName, and active. Given an array of strings representing a set of usernames, we can easily fetch all the users corresponding to that list of usernames:
NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] init];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"User"
inManagedObjectContext:moc];
[request setEntity:entity];
NSArray *userNames = [NSArray arrayWithObjects:#"user1", #"user2", #"user3", nil];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"userName IN %#", userNames];
[request setPredicate:predicate];
NSArray *users = [moc executeFetchRequest:request error:nil];
However, I want to fetch the complement of that set, i.e., I want all the users in core data that don't have the usernames specified in the userNames array. Does anyone have an idea how to approach this issue? I thought it would be simple enough to add a "NOT" in the predicate (i.e., "userName NOT IN %#"), but Xcode throws an exception saying the predicate format could not be parsed. I also tried using the predicate builder available for fetch requests with no luck. The documentation wasn't particularly helpful either. Suggestions? Comments? Thanks for all your help :)
In order to find the objects that aren't in your array, all you have to do is something like this:
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"NOT (userName IN %#)", userNames];
That should return a request of all the objects without the ones you specified
I am not strong at core data/objective-c but the predicate should be like the following statement;
[predicateFormat appendFormat:#"not (some_field_name in {'A','B','B','C'})"];
An example:
NSMutableString * mutableStr = [[NSMutableString alloc] init];
//prepare filter statement
for (SomeEntity * e in self.someArray) {
[mutableStr appendFormat:#"'%#',", e.key];
}
//excluded objects exist
if (![mutableStr isEqual:#""])
{
//remove last comma from mutable string
mutableStr = [[mutableStr substringToIndex:mutableStr.length-1] copy];
[predicateFormat appendFormat:#"not (key in {%#})", mutableStr];
}
//...
//use this predicate in NSFetchRequest
//fetchRequest.predicate = [NSPredicate predicateWithFormat:predicateFormat];
//...
Here's another useful example, showing how to take a list of strings, and filter out any which DON'T start with the letters A-Z:
NSArray* listOfCompanies = [NSArray arrayWithObjects:#"123 Hello", #"-30'c in Norway", #"ABC Ltd", #"British Rail", #"Daily Mail" #"Zylophones Inc.", nil];
NSPredicate *bPredicate = [NSPredicate predicateWithFormat:#"NOT (SELF MATCHES[c] '^[A-Za-z].*')"];
NSArray *filteredList = [listOfCompanies filteredArrayUsingPredicate:bPredicate];
for (NSString* oneCompany in filteredList)
NSLog(#"%#", oneCompany);
I use this kind of NSPredicate when I'm populating a UITableView with an A-Z index, and want an "everything else" section for items which don't start with a letter.

How do I get the last record of a Core Data database?

I have a core data entity called images that has just 2 fields:
imageName = NSString
timeStamp = NSNumber
I am trying to simulate a kind of stack LIFO (last in first out).
Inserting a new entry is easy but what about reading the last entry added to the entity?
All images are added with a timestamp, obtained by using
time_t unixTime = (time_t) [[NSDate date] timeIntervalSince1970];
an integer that is equal to the number of seconds since 1970
so, how do I retrieve the last inserted record of a core data (= the record that has the biggest timestamp number)???
thanks
Perform a fetch request, sorting the results by timeStamp.
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:...];
// Results should be in descending order of timeStamp.
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:#"timeStamp" ascending:NO];
[request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
NSArray *results = [managedObjectContext executeFetchRequest:request error:NULL];
Entity *latestEntity = [results objectAtIndex:0];
You might also want to restrict the number of results using NSFetchRequest's setFetchLimit:.
I have tried using the method that Chris Doble mentioned and found it to be very slow, especially if there are lot of records that would need to be pulled and checked against the timeStamp. If you want to speed things up, I am now setting an attribute called isMostRecent on my ManagedObject's that I may ever want to get the most recent from. When a new record is to be stored I just grab the most recent record that has this attribute set to YES and change it to NO then set the new record that is being stored to YES. The next time I need to grab to most recent record all I have to do is this...
+ (Photo*)latestPhotoForMOC:(NSManagedObjectContext*)context {
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:kCoreDataEntityNamePhoto
inManagedObjectContext:context];
[request setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"isMostRecent == %#", [NSNumber numberWithBool:YES]];
[request setPredicate:predicate];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"isMostRecent" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
NSError *error = nil;
NSMutableArray *mutableFetchResults = [[context executeFetchRequest:request error:&error] mutableCopy];
Photo* photo = nil;
if (mutableFetchResults && mutableFetchResults.count > 0) {
photo = [mutableFetchResults objectAtIndex:0];
}
return photo;
}
I have found this to be much faster. Yes, it requires a little more on your part to ensure it is used properly and that you don't ever end up with more than one record marked as isMostRecent but for me this was the best option.
Hope this helps someone else too.
In Swift 4, declare:
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let entity = [Entity]()
func getLastRecord() {
let entityCount = (entity.count - 1)
let lastRecord = entity[entityCount] // This is the las attribute of your core data entity
print(lastRecord)
}

How to determine number of objects in one-to-many relationship in CoreData

So, I've got a one-to-many relationship of Companies to Employees in CoreData (using a SQLite backend on iOS, if that's relevant). I want to create a predicate that only returns Companies that have 0 Employees associated with them. I could do it by getting all the Companies and iterating over them, but that would be (I assume) much slower.
Any ideas?
Thanks,
-Aaron
After trying #falconcreek's answer and getting an error (described in my comment on his answer), I did some googling and determined that the answer was
NSPredicate *noEmployeesPredicate = [NSPredicate predicateWithFormat:#"employees.#count == 0"];
Now everything works über efficiently. Thanks!
Assuming your Company -> Employee relationship is named "employees"
NSManagedObjectContext *moc = [self managedObjectContext];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:#"Company" inManagedObjectContext:moc];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:entityDescription];
// the following doesn't work
// NSPredicate *noEmployeesPredicate = [NSPredicate predicateWithFormat:#"employees = nil OR employees[SIZE] = 0"];
// use #count instead
NSPredicate *noEmployeesPredicate = [NSPredicate predicateWithFormat:#"employees = nil OR employees.#count == 0"];
[request setPredicate:predicate];
NSError *error = nil;
NSArray *array = [moc executeFetchRequest:request error:&error];
if (error)
{
// Deal with error...
}