我已经开始在练习 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/