如何在Open WithCompletionHandler之后返回结果:已完成

时间:2012-06-03 07:50:23

标签: objective-c ios xcode core-data block

想要在Coredata数据库中查询照片

这是我的代码

这是NSObjectSubclass类别

//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

视图控制器内部的代码

//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];
    }
}

连接它们的NSObject类。

 //  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

coredata只有实体名为“Photo”,它只有一个属性“name”。 问题是返回总是在块完成之前执行,并且总是返回NO。 测试代码here

或者在查询时我应该做一些比openWithCompletionHandler更多的事情吗?

2 个答案:

答案 0 :(得分:2)

您需要重新设计方法以异步工作,例如-openWithCompletionHandler:。它需要获取一个块,该块在知道答案时被调用,并且接收答案,无论是真还是假,作为参数。

然后,调用者应该传入一个块,该块执行在知道答案后应该发生的任何事情。

或者,或者,您应该延迟整个数据库中关注照片的逻辑块。这应该在开放完成后完成。

您必须显示更多代码才能获得更具体的建议。


因此,您可以将isPhoto...方法重写为:

+ (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);
}

然后你可以重做这个:

- (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];
        }
    }];
}

答案 1 :(得分:0)

试试

+(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;
}