Block的使用:(1)Block用于回调:
例:typedef void(^CallBackBlock)(int value);
////////////////////////////
@interface MainClass : NSObject
- (void)doSomething;
@end
@implementation MainClass
- (void)doSomething
{
AssitClass *assitClass = [[AssitClass alloc] init];
[assitClass assitSomethingCompletion:^(int value)
{
NSLog(@"%d",value);
//根据参数
}];
}
@end
////////////////////////////
@interface AssitClass : NSObject
- (void)assitSomethingCompletion:(CallBackBlock)completionBlock;
@end
@implementation AssitClass
- (void)assitSomethingCompletion:(CallBackBlock)completionBlock
{
//doSomething
int value = 0;//根据具体的逻辑赋值
completionBlock(value);
//如果Block有返回值这里获取,然后做一些其他操作。
}
@end
(2)Block用于并发;
例:dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
//doSomething
});
dispatch_async(dispatch_get_main_queue(), ^{
//更新UI
});
(3)Block用于遍历。
例:__block BOOL found = NO;
NSSet *stringSet = [NSSet setWithObjects: @"Alpha", @"Beta", @"Gamma", @"X", nil];
NSString *string = @"gamma";
[stringSet enumerateObjectsUsingBlock:^(id obj, BOOL *stop)
{
if ([obj localizedCaseInsensitiveCompare:string] == NSOrderedSame)
{
*stop = YES;//调用Block那边怎么根据stop的值停止遍历?
found = YES;
}
}];
Block的实现请参考:http://blog.csdn.net/joywii/article/details/15340523 |