iOS 之单例 代理 通知

来源:互联网 发布:商务中国域名转出 编辑:程序博客网 时间:2024/06/15 12:06

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

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.delegaterespondsToSelector:@selector(appViewClickedDownloadButton:)]) {

        [self.delegateappViewClickedDownloadButton:self];

    }

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



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

1.发送通知

    [[NSNotificationCenterdefaultCenter]postNotificationName:@"notice"object:selfuserInfo:@{@"infoName":@"我是发送者"}];

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

1>注册通知

    [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(noticeActin:)name:@"notice"object:nil];

- (void)noticeActin:(NSNotification *)notice

{

    //输出:我是发送者

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

}

2>移除通知

- (void)dealloc

{

    [[NSNotificationCenterdefaultCenter]removeObserver:@"notice"];

}

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



0 0
原创粉丝点击