#import <Foundation/Foundation.h>
#import "AFNetworking.h"
typedefvoid(^Myblock)(id responseObj);
// - 在函数中 用(void(^)(id responseObj)) 代替 (Myblock)
@interface CFHttpTool :NSObject
+ (void)get:(NSString *)url params:(NSDictionary *)params success:(Myblock)success failure:(void (^)(NSError *error))failure;
+ (void)get:(NSString *)url params:(NSDictionary *)params success:(Myblock)success failure:(void (^)(NSError *))failure
{
// 1.获得请求管理者
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManagermanager];
mgr.responseSerializer = [AFHTTPResponseSerializerserializer];//使用这个将得到的是NSData
NSString *fileName = url;
// 2.发送GET请求
[mgrGET:urlparameters:params
success:^(AFHTTPRequestOperation *operation,id responseObj) {
if (success) {
NSDictionary *result = [NSDictionaryresultWithResponseObj:responseObj];
[CFDataCacheToolsaveDictionary:resultfileName:fileName];
success(result);
}
}failure:^(AFHTTPRequestOperation *operation,NSError *error) {
NSDictionary *result = [CFDataCacheTooldictionaryWithFileName:fileName];
if (result) {
if (success) {
success(result);
}
}elseif (failure) {
failure(error);
}
}];
}
[CFHttpToolpost:@"http://cfnet.org.cn/index2.php?m=android&c=Home&a=askindex"params:paramssuccess:^(id responseObj) {
NSArray *knowQAs = [CFKnowQAobjectArrayWithKeyValuesArray:responseObj];
for (CFKnowQA *knowQAin knowQAs) {
CFKnowQAFrame *knowQAFrame = [[CFKnowQAFramealloc]init];
knowQAFrame.knowQA = knowQA;
[self.knowQAFramesaddObject:knowQAFrame];
}
[self.tableViewreloadData];
}failure:^(NSError *error) {
}];
SecondViewController 中的方法
typedef BOOL(^QGblock)(int a);
- (void)setBlcok:(QGblock)block{
BOOL IS5 = block(10);
if (IS5) {
NSLog(@"5");
}else{
NSLog(@"BUSHI 5");
}
}
FirstViewController 的调用
SecondViewController * secondVC = [[SecondViewController alloc]init];
[secondVC setBlcok:^BOOL(int a) {
if (a==5) {
return YES;
}else{
return NO;
}
}];
[self.navigationController pushV
/**
* 使用block会有循环引用的风险---对外部变量的一个强引用
- self要小心(借助 delloc判断是否释放)
- 为了保险起见 将所有的self 替换为 __weak typeof (self) weakSelf = self;
*/
void test5();
int main(int argc,constchar * argv[])
{
test5();
return 0;
}
int num = 10;
void test5()
{
void (^block)() = ^{
// block内部能够一直引用全局变量
NSLog(@"----num=%d",num);
};
num = 20;
block();
}
void test4()
{
static int age =10;
void (^block)() = ^{
// block内部能够一直引用被static修饰的变量打印 block 里边的 age的最后一次赋值的时候的值为----age=20
NSLog(@"----age=%d", age);
};
age = 20;
block();
}
void test3()
{
__block int age =10;
void (^block)() = ^{
// block内部能够一直引用被__block修饰的变量打印 block里边的 age 的最后一次赋值的时候的值为----age=20
NSLog(@"----age=%d", age);
};
age = 20;
block();
}
void test2()
{
int age = 10;
age = 20;
void (^block)() = ^{
// 普通的局部变量,block内部只会引用它初始的值(block定义那一刻),不能跟踪它的改变打印 block 里边的 age 的在这段代码之前最后一次赋值的时候的值 为----age=20
NSLog(@"----age=%d", age);
};
block();
}
void test()
{
int age = 10;
void (^block)() = ^{
// ----age=10
NSLog(@"----age=%d", age);
};
block();
}
/**
int (^block)(int) = ^(int a){
NSLog(@"----age=%d", age);
return 10;
};
*/