Search code examples
iosobjective-cdatabasensfetchrequest

Fetch form database with try catch


I wrote a fetch method in routine way:

-(FXPCallLog *)getCallLogWithID:(NSString *)logID{
    NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:[[FXPCallLog class] description]];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"logID = %@", logID];
    [request setPredicate:predicate];

    NSError *err = nil;
    NSArray *result = [self.moc executeFetchRequest:request error:&err];
    if (!err && result && result.count > 0){
        FXPCallLog *foundLog = (FXPCallLog *)[result firstObject];
        return foundLog;
    }
    return nil;
}

And it works fine.

But when I change the result to:

NSArray *result = [[NSArray alloc] init];
@try {
    result = [NSArray arrayWithArray:[self.moc executeFetchRequest:request error:&err]];
} @catch (NSException *exception) {
    NSLog(@"deadlock :/");
} @finally {
    return nil;
}

It gets me wrong result!

I can't figure it out what's the difference between these two.

Why these are different ?


In Addition

I've added try-catch for handling deadlock.

Any advice and suggestions will be greatly appreciated.


Solution

  • @finally is always run, regardless of the exception being thrown or not. Since you put return nil; there, all your results get discarded. As always - more in the docs.