zoukankan      html  css  js  c++  java
  • iOS 关于iOS开发中的delegate

    有A、B两个对象,A要完成某件事,想让B帮它做。

    这时候,A中就要实例化一个B的对象b,A还要在头文件中声明协议,然后在B中实现协议中对应的方法。

    这时候再把A的delegate设置为b,在需要的地方,就可以调用B来完成任务了。

    //  main.m
    #import <Foundation/Foundation.h>
    #import "A.h"
    #import "B.h"
    int main(int argc, const char * argv[]) {
        @autoreleasepool {
            // insert code here...
            A *a = [[A alloc] init];
            B *b = [[B alloc] init];
            a.delegate = b;
            [a doSomething];
        }
        return 0;
    }
    
    
    //  A.h
    #import <Foundation/Foundation.h>
    #import "CertainDelegate.h"
    
    @interface A : NSObject
    @property (weak,nonatomic) id<CertainDelegate> delegate;
    - (void)doSomething;
    @end
    
    
    
    //  A.m
    #import "A.h"
    #import "B.h"
    
    @interface A ()
    @end
    
    @implementation A
    - (void)doSomething{
        [_delegate requiredFunc];
    }
    
    @end
    
    
    
    //  B.h
    #import <Foundation/Foundation.h>
    #import "CertainDelegate.h"
    
    @interface B : NSObject<CertainDelegate>
    @end
    
    
    
    //  B.m
    #import "B.h"
    
    @interface B ()
    @end
    
    @implementation B
    -(void)requiredFunc{
        NSLog(@"requiredFunc is running.");
    }
    @end
    
    
    
    
    //  CertainDelegate.h
    #import <Foundation/Foundation.h>
    
    @protocol CertainDelegate <NSObject>
    - (void)requiredFunc;
    @end

    推荐深度阅读文章

    Stay hungry,stay foolish.
  • 相关阅读:
    如何设计一个百万级用户的抽奖系统?
    服务注册发现
    消息列队7
    消息列队6
    bzoj 4771: 七彩树
    [SDOI2013]刺客信条
    bzoj 5291: [Bjoi2018]链上二次求和
    51nod 1245 Binomial Coefficients Revenge
    bzoj 5308: [Zjoi2018]胖
    bzoj 5294: [Bjoi2018]二进制
  • 原文地址:https://www.cnblogs.com/ficow/p/5034750.html
Copyright © 2011-2022 走看看