ios - 解析中的 block

标签 ios objective-c

我已经开始在练习 iOS 应用程序中使用 Parse(我使用 Cocoapods 下载),但我在理解某些概念时遇到了一些困难。

到目前为止我已经写了这段代码:

- (IBAction)saveUserButtonClicked:(id)sender {
    PFObject *loginCredentials = [PFObject objectWithClassName:@"LoginCredentials"];
    loginCredentials[@"name"] = self.usernameTextField.text;
    loginCredentials[@"password"] = self.passwordTextField.text;


    [loginCredentials saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if(error.code == kPFErrorConnectionFailed){
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Please check you connection" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil];
            [alertView show];
        }else if(succeeded && !error){
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Save" message:@"Your object saved" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil];
            [alertView show];
        }else if(error){
            NSLog(@"%@", error);
        }

    }];
}

我的主要问题是使用 saveInBackGroundWithBlock 的目的是什么。我可以通过这样做来做同样的逻辑吗:

[loginCredentials saveInBackground];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Save" message:@"Your object saved" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles: nil];
[alertView show];

只有当我们想访问成功变量和错误变量时,该 block 才有用吗?

最佳答案

saveInBackgroundWithBlock 中,保存操作在后台线程中执行,而不是在主线程(UI 使用的线程)中执行,一旦它结束执行,它就会回调 block 来执行它。不使用主线程执行此保存操作会使用户界面响应,同时在另一个线程中执行保存。

您可以使用 save 方法在主线程中进行保存操作,然后根据成功显示警报,但您将完全阻塞用户界面,这不是最佳做法,除非它必须在应用程序上继续。

bool succeeded = [loginCredentials save];

关于ios - 解析中的 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32598295/

相关文章:

objective-c - 无法加载localizable.strings

ios - 将设备旋转为横向时的 UICollectionViewFlowLayout 大小警告

ios - 解释特征属性(iOS 和 BLE)

ios - GTM 容器的预览和更新版本 | iOS

ios - 恢复购买功能 - Swift

iphone - 对字典进行排序并更改索引

objective-c - 如何安全地将对象放入 __unsafe_unretained 数组中?

ios - MakeSchool MakeNotes swift 教程 |创建全局变量

ios - Swift 看不到使用 block 的 objc 类函数

objective-c - ARC时代的属性(property)与ivar