闭包 * block * 代理 * 使用实例

2016-05-26  本文已影响34人  武一顶顶

一.闭包

import UIKit
import AFNetworking

enum RequestType {
    case GET
    case POST
}

class NetworkTools: AFHTTPSessionManager {
    // 1.将NetworkTools设置成单例
    static let shareIntance : NetworkTools = {
        let tools = NetworkTools()
        
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        
        return tools
    }()
}
// MARK:- 封装网络请求
extension NetworkTools {
    func request(requestType : RequestType, urlString : String, parameters : [String : AnyObject], finished : (result : AnyObject?, error : NSError?) -> ()) {
        
        // 1.定义成功后的闭包
        let successCallBack = { (task : NSURLSessionDataTask, result : AnyObject?) -> Void in
            finished(result: result, error: nil)
        }
        
        // 2.定义失败后的闭包
        let failureCallBack = { (task : NSURLSessionDataTask?, error : NSError) -> Void in
            finished(result: nil, error: error)
        }
        
        // 3.发送网络请求
        if requestType == .GET {
            GET(urlString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack)
        } else {
            POST(urlString, parameters: parameters, progress: nil, success: successCallBack, failure: failureCallBack)
        }
    }
}

// MARK:- 请求首页数据
extension NetworkTools {
    func loadHomeData(finished : (result : [[String : AnyObject]]?, error : NSError?) -> ()) {
        // 1.获取请求的URLString
        let urlString = "http://mobapi.meilishuo.com/2.0/twitter/popular.json"
        
        // 2.获取请求的参数
        let parameters = ["offset" : "0", "limit" : "30", "access_token" : "b92e0c6fd3ca919d3e7547d446d9a8c2"]
        
        // 3.发送网络请求
        request(.GET, urlString: urlString, parameters: parameters) { (result, error) -> () in

/**********此处就可以拿到闭包的参数,就相当于把数据传出来了******/
            // 1.判断是否有错误
            if error != nil {
                finished(result: nil, error: error)
            }
            
            // 2.获取结果
            guard let result = result as? [String : AnyObject] else {
                finished(result: nil, error: NSError(domain: "data error", code: -1011, userInfo: nil))
                return
            }
            
            // 3.将结果回调
            finished(result: result["data"] as? [[String : AnyObject]] , error: nil)
        }
    }
}

二. 代理

#import <UIKit/UIKit.h>

@protocol HostViewDelegate <NSObject>

- (void)pushViewControllerWith:(UIButton *)btn;
@end

@interface HostView : UIView

@property (nonatomic, weak) id<HostViewDelegate>Delegate;
@end
- (void)clickButtonWith:(UIButton *)btn
{
    //int tag = (int)btn.tag;
   // self.block(tag);  //此处是block写法
  
    
   if ([self.Delegate respondsToSelector:@selector(pushViewControllerWith:)] ) {
       [self.Delegate pushViewControllerWith:btn];
   }
}
@interface MineViewController ()<HostViewDelegate>
hostView.Delegate = self;
- (void)pushViewControllerWith:(UIButton *)btn
{
    UIViewController *vc = self.controllerArray[btn.tag];
    NSLog(@"%@+++++++",vc);
    [self.navigationController pushViewController:vc animated:YES];
}

三. block

3.1思想

 A.block(int) = ^(int a){
      这样 在此括号里就能拿到 A 类传递过来的a值 ,实现了代理传值方法
}

3.2实例


#import <UIKit/UIKit.h>

//@protocol HostViewDelegate <NSObject>
//
//- (void)pushViewControllerWith:(UIButton *)btn;
//
//@end

@interface HostView : UIView

//@property (nonatomic, weak) id<HostViewDelegate>Delegate;

@property (nonatomic, strong) void(^block)(int);

@end
  - (void)clickButtonWith:(UIButton *)btn
{
    int tag = (int)btn.tag;
    self.block(tag);
  
    
//    if ([self.Delegate     //此处是delegate写法  respondsToSelector:@selector(pushViewControllerWith:)] ) {
//        [self.Delegate pushViewControllerWith:btn];
//    }
}
    hostView.block = ^( int tag ){
        UIViewController *vc = self.controllerArray[tag];
        NSLog(@"%@+++++++",vc);
        [self.navigationController pushViewController:vc animated:YES];
    };
上一篇下一篇

猜你喜欢

热点阅读