Kyle Fang
Kyle Fang

Reputation: 1209

how to return result after OpenWithCompletionHandler: is complete

Want to query a photo in the Coredata database

this is my code

this is the NSObjectSubclass category

//Photo+creak.h

#import "Photo+creat.h"

@implementation Photo (creat)

+(Photo *)creatPhotoByString:(NSString *)photoName inManagedObjectContext:(NSManagedObjectContext *)context{
    Photo *picture = nil;

    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Photo"];
    request.predicate = [NSPredicate predicateWithFormat:@"name = %@", photoName];

    NSArray *matches = [context executeFetchRequest:request error:nil];
    if (!matches || [matches count]>1) {
        //error
    } else if ([matches count] == 0) {
        picture = [NSEntityDescription insertNewObjectForEntityForName:@"Photo" inManagedObjectContext:context];
        picture.name = photoName;
    } else {
        picture = [matches lastObject];
    }
    return picture;
}

+ (BOOL)isPhoto:(NSString *)photoName here:(NSManagedObjectContext *)context{
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Photo"];
    request.predicate = [NSPredicate predicateWithFormat:@"name = %@", photoName];
    NSArray *matches = [context executeFetchRequest:request error:nil];
    switch ([matches count]) {
        case 1:
            return YES;
            break;
        default:
            return NO;
            break;
    }
}
@end

code inside of view controller

//View Controller
- (IBAction)insertData:(UIButton *)sender {
    NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    url = [url URLByAppendingPathComponent:@"test"];
    UIManagedDocument *defaultDocument = [[UIManagedDocument alloc] initWithFileURL:url];
    if (![[NSFileManager defaultManager] fileExistsAtPath:[url path]]) {
        [defaultDocument saveToURL:defaultDocument.fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:NULL];
    }
    [defaultDocument openWithCompletionHandler:^(BOOL success) {
        [Photo creatPhotoByString:@"test" inManagedObjectContext:defaultDocument.managedObjectContext];
        [defaultDocument saveToURL:defaultDocument.fileURL forSaveOperation:UIDocumentSaveForOverwriting completionHandler:NULL];
    }];
    [sender setTitle:@"Okay" forState:UIControlStateNormal];
    [sender setEnabled:NO];
}

- (IBAction)queryFromDatabase:(UIButton *)sender {
    NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    url = [url URLByAppendingPathComponent:@"test"];
    UIManagedDocument *defaultDocument = [[UIManagedDocument alloc] initWithFileURL:url];
    BOOL isItWorking = [checkPhoto isPhoto:@"test" inManagedDocument:defaultDocument];
    if (isItWorking) {
        [sender setTitle:@"Okay" forState:UIControlStateNormal];
    } else {
        [sender setTitle:@"NO" forState:UIControlStateNormal];
    }
}

The NSObject Class that hook them up.

 //  checkPhoto.m
#import "checkPhoto.h"
@implementation checkPhoto
+ (BOOL)isPhoto:(NSString *)photoToCheck inManagedDocument:(UIManagedDocument *)document{
    __block BOOL isPhotoHere = NO;
    if (document.documentState == UIDocumentStateClosed) {
        [document openWithCompletionHandler:^(BOOL success) {
            isPhotoHere = [Photo isPhoto:photoToCheck here:document.managedObjectContext];
        }];
    }
    return isPhotoHere;
}
@end

The coredata only have on Entity named "Photo", and it got only one attribute "name". The problem is that the return always get execute before the block is complete and always return NO. Test code here

Or should I do something else than openWithCompletionHandler when querying?

Upvotes: 1

Views: 1617

Answers (2)

Ken Thomases
Ken Thomases

Reputation: 90621

You need to rework your method to work asynchronously, like -openWithCompletionHandler:. It needs to take a block which is invoked when the answer is known and which receives the answer, true or false, as a parameter.

Then, the caller should pass in a block that does whatever is supposed to happen after the answer is known.

Or, alternatively, you should delay the whole chunk of logic which cares about the photo being in the database. It should be done after the open has completed.

You'd have to show more code for a more specific suggestion.


So, you could rework the isPhoto... method to something like:

+ (BOOL)checkIfPhoto:(NSString *)photoToCheck isInManagedDocument:(UIManagedDocument *)document handler:(void (^)(BOOL isHere))handler {
    if (document.documentState == UIDocumentStateClosed) {
        [document openWithCompletionHandler:^(BOOL success) {
            handler([Photo isPhoto:photoToCheck here:document.managedObjectContext]);
        }];
    }
    else
        handler(NO);
}

Then you can rework this:

- (IBAction)queryFromDatabase:(UIButton *)sender {
    NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    url = [url URLByAppendingPathComponent:@"test"];
    UIManagedDocument *defaultDocument = [[UIManagedDocument alloc] initWithFileURL:url];
    [checkPhoto checkIfPhoto:@"test" isInManagedDocument:defaultDocument handler:^(BOOL isHere){
        if (isHere) {
            [sender setTitle:@"Okay" forState:UIControlStateNormal];
        } else {
            [sender setTitle:@"NO" forState:UIControlStateNormal];
        }
    }];
}

Upvotes: 2

JP Hribovsek
JP Hribovsek

Reputation: 6707

Try that

+(BOOL)isPhoto:(Photo *)photo inDataBase:(UIManagedDocument *)defaultDocument{
 __block BOOL isPhotoThere = NO;
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
[defaultDocument openWithCompletionHandler:^(BOOL success) {
    [defaultDocument.managedObjectContext performBlock:^{
        isPhotoThere = [Photo checkPhoto:photo];
        dispatch_semaphore_signal(sema);
    }];
 }];
 dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
 dispatch_release(sema);
 return isPhotoThere;
}

Upvotes: 0

Related Questions