cari

Rumah  >  Soal Jawab  >  teks badan

objective-c - ios中,用工厂方法如何return block里的值?

正在学习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中文网2767 hari yang lalu487

membalas semua(3)saya akan balas

  • 高洛峰

    高洛峰2017-04-18 09:57:47

    Asynchronous:

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

    Penyegerakan:

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

    balas
    0
  • 高洛峰

    高洛峰2017-04-18 09:57:47

    1. Tambahkan bentuk kaedah kilang pada blok dan objek panggil balik blok

    2. dispatch_semaphore_t, tunggu sebelum pulang.

    balas
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-18 09:57:47

    Anda layak mempunyai kumpulan GCD Jika anda menggunakan swift, blok @escaping akan melakukannya. .

    balas
    0
  • Batalbalas