objective-c - ios中,用工厂方法如何return block里的值?
PHP中文网
PHP中文网 2017-04-18 09:55:47
0
3
479

正在学习Leancloud,想用一个工厂方法来封装查询代码,但是不能return block里的值,直接return objectID是空值,求指教,谢谢!

+ (NSString *)getObjectIDbyUsername:(NSString *)_username
{
    __block NSString *objectID = NULL;
    NSString *username = [NSString stringWithFormat:@"^%@$",_username];
    AVQuery *query = [AVQuery queryWithClassName:@"_User"];
    [query whereKey:@"username" containsString:username];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        objectID = [objects valueForKey:@"objectId"];
    }];

    return objectID;
}
PHP中文网
PHP中文网

认证0级讲师

全部回覆(3)
小葫芦

非同步:

+ (void)getObjectIDbyUsername:(NSString * )_username compelete:(void(^)(NSString * objectID))compelete{
    
    NSString *username = [NSString stringWithFormat:@"^%@$",_username];
    AVQuery *query = [AVQuery queryWithClassName:@"_User"];
    [query whereKey:@"username" containsString:username];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (compelete) {
            compelete(nil);
            compelete = nil;
        }
    }];
}

// use:

[HTBaseContainer getObjectIDbyUsername:@"userName" compelete:^(NSString *objectID) {
    
}];

同步:

+ (NSString *)getObjectIDbyUsername:(NSString *)_username
{
    dispatch_semaphore_t signal = dispatch_semaphore_create(1);
    
    __block NSString *objectID = NULL;
    NSString *username = [NSString stringWithFormat:@"^%@$",_username];
    AVQuery *query = [AVQuery queryWithClassName:@"_User"];
    [query whereKey:@"username" containsString:username];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        objectID = [objects valueForKey:@"objectId"];
        dispatch_semaphore_signal(signal);
    }];
    
    dispatch_semaphore_wait(signal, DISPATCH_TIME_FOREVER);
    return objectID;
}
小葫芦
  1. 把工廠方法的形參加一個block, block 回調objectID

  2. dispatch_semaphore_t, 在return前一直是wait.

伊谢尔伦

GCD group你值得擁有,假如用swift的話一個@escaping block就搞定了。 。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!