【问题标题】:iOS return bool value in blockiOS 在块中返回 bool 值
【发布时间】:2013-02-28 19:35:06
【问题描述】:

我正在尝试从我调用的包含块的类方法中返回一个布尔值。我收到错误,发送不兼容的块指针类型......我该如何解决这个问题?我只想知道我调用的类方法是否完成有无错误...

+ (BOOL)saveSelectedDepartmentsToParse:(NSMutableDictionary *)dictionary {

    NSArray *array = [dictionary allKeysForObject:@"YES"];
    NSMutableArray *trimmedArray = [[NSMutableArray alloc] init];

    for (NSString *string in array) {

        NSString *final = [string removeAllInvalidCharacters];
        [trimmedArray addObject:final];
    }

    NSLog(@"Array = %@", trimmedArray);

    PFInstallation *currentInstallation = [PFInstallation currentInstallation];

    [currentInstallation removeObjectForKey:@"channels"];
    [currentInstallation addObjectsFromArray:trimmedArray forKey:@"channels"];
    [currentInstallation saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {

        if (error == nil) {

            NSLog(@"Parse Save Succeeded");

            [self saveDepartmentsDictionary:dictionary];
        }
        else {

            NSLog(@"Parse Save Failed, %@", error.localizedDescription);
        }
    }];
}

【问题讨论】:

标签: ios boolean block class-method


【解决方案1】:

来自区块关键字InBackground:

[currentInstallation saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
    if (error == nil) {
        NSLog(@"Parse Save Succeeded");
        [self saveDepartmentsDictionary:dictionary];
    } else {
        NSLog(@"Parse Save Failed, %@", error.localizedDescription);
    }
}];

我猜这个块是异步调用的。

如果你想得到结果,你可以在这里等到块被执行,但这会使saveInBackgroundWithBlock无用。

所以 NSNotification 可能会更好:

[currentInstallation saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
    if (error == nil) {
        NSLog(@"Parse Save Succeeded");
        [self saveDepartmentsDictionary:dictionary];
        [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationParseSaveSucceeded object:nil];
    } else {
        NSLog(@"Parse Save Failed, %@", error.localizedDescription);
        [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationParseSaveFailed object:nil];
    }
}];

【讨论】:

    【解决方案2】:

    我只想知道我调用的类方法

    这是对异步代码工作原理的误解。当您向saveInBackgroundWithBlock: 提供块时,该代码不会立即执行。它在稍后由 Parse 框架执行,如果块被定义为有一个,则 Parse 的任何部分都将获得返回值,但事实并非如此。你的块在你写它的时候没有被执行,所以你不能在你写它的时候返回任何东西。

    您的代码没有调用该块,并且您不能从它向您的代码返回值。这样做没有意义。如果您的代码的另一部分想知道保存何时完成,您将需要使用返回值以外的其他机制,例如从您的块中调用方法、发布通知或键值观察。

    【讨论】:

    • 我指的是我写的方法,它是一个类方法。我知道 saveInBackground 不是类方法,正如它所说的那样,它是一个实例方法。
    • 啊,我明白了。我的其余答案是有效的。类方法在块被执行之前返回。
    猜你喜欢
    • 2015-06-30
    • 1970-01-01
    • 2021-11-11
    • 2020-09-10
    • 2013-07-02
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    相关资源
    最近更新 更多