在使用 Swift
和 Objective-C
时,我同时遇到了完成处理程序和块的问题。当我在谷歌上搜索 Swift
中的块时,它显示的是完成处理程序的结果!有人能告诉我关于 Swift
和 Objective-C
中完成处理程序和块的区别吗?
在使用 Swift
和 Objective-C
时,我同时遇到了完成处理程序和块的问题。当我在谷歌上搜索 Swift
中的块时,它显示的是完成处理程序的结果!有人能告诉我关于 Swift
和 Objective-C
中完成处理程序和块的区别吗?
在这里,您可以轻松区分块和完成处理程序,事实上两者都是块,请参见下面的详细信息。
块:
块是添加到 C、Objective-C 和 C++ 的语言级功能,它允许您创建不同的代码段,这些代码段可以像值一样传递到方法或函数中。块是 Objective-C 对象,这意味着它们可以添加到类似 NSArray 或 NSDictionary 的集合中。
语法: ReturnType (^blockName)(Parameters) 请参见示例:
int anInteger = 42;
void (^testBlock)(void) = ^{
NSLog(@"Integer is: %i", anInteger); // anInteger outside variables
};
// calling blocks like
testBlock();
带参数的块:
double (^multiplyTwoValues)(double, double) =
^(double firstValue, double secondValue) {
return firstValue * secondValue;
};
// calling with parameter
double result = multiplyTwoValues(2,4);
NSLog(@"The result is %f", result);
完成处理程序:
完成处理程序是使用块实现回调功能的一种方法(技术)。
完成处理程序不过是一个简单的块声明,作为参数传递给需要在稍后时间进行回调的方法。
注意: 完成处理程序应该总是作为方法中最后一个参数。一个方法可以有任意多的参数,但始终将完成处理程序作为参数列表中的最后一个参数。
示例:
- (void)beginTaskWithName:(NSString *)name completion:(void(^)(void))callback;
// calling
[self beginTaskWithName:@"MyTask" completion:^{
NSLog(@"Task completed ..");
}];
使用UIKit
类的方法示例更多。
[self presentViewController:viewController animated:YES completion:^{
NSLog(@"xyz View Controller presented ..");
// Other code related to view controller presentation...
}];
[UIView animateWithDuration:0.5
animations:^{
// Animation-related code here...
[self.view setAlpha:0.5];
}
completion:^(BOOL finished) {
// Any completion handler related code here...
NSLog(@"Animation over..");
}];
块: Obj-c
- (void)hardProcessingWithString:(NSString *)input withCompletion:(void (^)(NSString *result))block;
[object hardProcessingWithString:@"commands" withCompletion:^(NSString *result){
NSLog(result);
}];
闭包: Swift
func hardProcessingWithString(input: String, completion: (result: String) -> Void) {
...
completion("we finished!")
}
I am hope this will help.
First Step:
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
-(void)InsertUser:(NSString*)userName InsertUserLastName:(NSString*)lastName widthCompletion:(void(^)(NSString* result))callback;
@end
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
-(void)InsertUser:(NSString *)userName InsertUserLastName:(NSString*)lastName widthCompletion:(void (^)(NSString* result))callback{
callback(@"User inserted successfully");
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self InsertUser:@"Ded" InsertUserLastName:@"Moroz" widthCompletion:^(NSString *result) {
NSLog(@"Result:%@",result);
}];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end