iOS 之单例 代理 通知

/******************单例******************/

1> Singleton.h 声明方法

//共享单例,便于其他类访问

+ (instancetype)sharedSingleton;

2> Singleton.m 实现方法

/**

 1.重写allocWithZone创建一个静态变量用于dispatch_once实例化

 2.+sharedXXX方便调用

 */


+ (id)allocWithZone:(struct_NSZone *)zone

{

    staticSingleton *singleton =nil;

    

    staticdispatch_once_t onceToken;

    

    //dispatch_once 保证只会被执行一次

    dispatch_once(&onceToken, ^{

        

        singleton = [superallocWithZone:zone];

    });

    return singleton;

}


+ (instancetype)sharedSingleton

{

   return [[selfalloc]init];

}


3> 创建方法

    Singleton *single1 = [SingletonsharedSingleton];

    Singleton *single2 = [SingletonsharedSingleton];

    Singleton *single3 = [[Singletonalloc]init];

    

    //输出同样的地址,保证只被创建一次

    NSLog(@"single1=%p single2=%p single3=%p ",single1,single2,single3);

/******************单例******************/


/******************代理******************/

 用于消息传递,传值等。


.h类中

// 声明一个协议

@protocol MJAppViewDelegate <NSObject>

@optional

- (void)appViewClickedDownloadButton:(MJAppView *)appView;


/**

 *  代理

 */

@property (nonatomic, weak) id<MJAppViewDelegate> delegate;


.m类中

    if ([self.delegate respondsToSelector:@selector(appViewClickedDownloadButton:)]) {

        [self.delegate appViewClickedDownloadButton:self];

    }

/******************代理******************/



/******************通知******************/

1.发送通知

    [[NSNotificationCenter defaultCenter]postNotificationName:@"notice" object:self userInfo:@{@"infoName":@"我是发送者"}];

2.在所要接收的控制器里面

1>注册通知

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(noticeActin:) name:@"notice" object:nil];

- (void)noticeActin:(NSNotification *)notice

{

    //输出:我是发送者

    NSLog(@"%@",notice.userInfo[@"infoName"]);

}

2>移除通知

- (void)dealloc

{

    [[NSNotificationCenter defaultCenter]removeObserver:@"notice"];

}

/******************通知******************/



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值