如何在Objective-C中聲明一個Block?
接下來正文中出現(xiàn)詞語定義:
returnType:
返回類型鲤遥, NSInteger斋日、BOOL、int挠羔、...
blockName:
block名稱井仰,自己定義
parameterTypes:
參數(shù)類型 ,NSInteger破加、BOOL糕档、int、...
parameters :
參數(shù)類型 +名 稱 拌喉,NSInteger index, BOOL flag ...
someObject :
對象速那,實例對象 、類對象尿背、self端仰、...
-
局部變量
returnType
(^blockName
)(parameterTypes
) = ^returnType
(parameters
) {...
};
NSInteger (^myblock)(BOOL) = ^NSInteger(BOOL flag) {
//code
if(flag) return 1
return 0;
};
-
屬性
@property (nonatomic, copy) returnType
(^blockName
)(parameters
);
@property (nonatomic, copy) NSInteger (^myblock)(BOOL flag);
-
方法參數(shù)
-(void)someMethodWithBlock:(returnType
(^)(parameters
))blockName
;
- (void)someMethodWithBlock:(NSInteger(^)(BOOL flag))myblock
{
//code
NSInteger index = myblock(YES);
//處理返回值 index
}
-
方法調(diào)用的參數(shù)
[someObject
someMethodWithBlock:^returnType
(parameters
) {...
}];
[self someMethodWithBlock:^NSInteger(BOOL flag) {
///code
if (flag) return 1;
return 0;
}];
-
C函數(shù)的參數(shù):
void
SomeFunctionWithBlock(returnType
(^blockName
)(parameterTypes
));void someMethodWichBlock(NSInteger(^myblock)(BOOL)){ //code NSInteger index = myblock(YES); //處理返回值 index };
-
typedef:
typedef returnType
(^blockName
)(parameters
);
blockName
aBlock = ^returnType
(parameters
) {...
};
typedef NSInteger (Myblock)(BOOL flag);
//調(diào)用
Myblock block = ^NSInteger(BOOL flag){
//code
if(flag)return 1;
return 0;
};