Reputation: 12194
Hey guys, I have this function:
//retrieves checksum within core data store, returns 0 if a checksum has not been stored
-(double)getStoredChecksum {
NSError *error;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"DataFeedManager" inManagedObjectContext:[self managedObjectContext]];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [[self managedObjectContext] executeFetchRequest:fetchRequest error:&error];
//+for (NSManagedObject* item in fetchedObjects) //REMOVE
//+[[self managedObjectContext] deleteObject:item]; //REMOVE FOR CLEARING CHECKSUM CONTENTS
if ([fetchedObjects count] == 0){ //array is empty
NSLog(@"FETCHED OBJECTS IS EMPTY");
checksumStored = NO;
return 0;
}
if (fetchedObjects == nil) {
NSLog(@"Error while fetching\n%@",
([error localizedDescription] != nil) ? [error localizedDescription] : @"Unknown Error");
}
if ([fetchedObjects count] > 1)
NSLog(@"====BAD:Multiple Checksums Retrieved!!!!====");
checksumStored = YES;
double returnable = [[[fetchedObjects objectAtIndex:0] valueForKey:@"lastUpdateCheckSum"] doubleValue];
return returnable;
}//getStoredChecksum()
As you can see, it executes a fetch request, however I am unsure of how to check if an error occurred. As you can see, I am checking to see if the array is empty via [fetchedObjects count] == 0
however, I heard somewhere that if the error occurs and the array is nil, 0 is returned for count as well, thus it is safe to test for array emptiness that way, but it masks my check for a null array. Thus the problem is that I have no definitive way of checking if an error occurred. Any thoughts on how I should go about doing this?
Thanks in advance!
EDIT:
How would I check for an error in this case?
NSUInteger numEntities = [[self managedObjectContext] countForFetchRequest:fetchRequest error:&error];
As NSUInteger is specified as an unsigned int, so I can't even assign it a value of -1 and check for a -1 later if I wanted to.
Upvotes: 1
Views: 698
Reputation: 16701
Set error
to nil
before calling executeFetchRequest::
. If error
is not nil
after then it was set and thus an error occured.
The reason the count
check is masking the nil
check is because any message sent to nil
returns nil
which in this case is also 0. This can be easily fixed by checking for nil
first, or modify your if
statement so it is as followed:
if (fetchedObjects && [fetchedObjects count] == 0){
For the case with countForFetchRequest::
NSNotFound
is returned when an error occurs, so just check for that.
Upvotes: 2
Reputation: 13612
Copy & pasted from the docs for countForFetchRequest:error:
Return Value
The number of objects a given fetch request would have returned if it had been passed to executeFetchRequest:error:, or NSNotFound if an error occurs.
So,
if (numEntities == NSNotFound) {
// Handle the error
}
Upvotes: 2