/******************单例******************/
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"];
}
/******************通知******************/