单例 //.h 1 + (Instannce *)shareInstance; //.m
1 static Instannce *instance = nil; 2 @implementation Instannce 3 //定义一个创建单例对象的方法 4 + (Instannce *)shareInstance { 5 if (instance == nil) { 6 instance = [[Instannce alloc] init]; 7 } 8 return instance; 9 } 10 //使用alloc的时候调用的方法instancetype 11 + (id)allocWithZone:(struct _NSZone *)zone { 12 if (instance == nil) { 13 instance = [super allocWithZone:zone]; 14 } 15 return instance; 16 } 17 - (id)copy { 18 return self; 19 } 20 - (id)retain { 21 return self; 22 } 23 - (NSUInteger)retainCount { 24 //返回无符号最大值 25 return UINT_MAX; 26 } 27 - (oneway void)release { 28 //什么也不做 29 }
代理 //.h
1 @protocol GetMessageProtocol <NSObject > 2 - (void)getNum:(NSString *)num withPassWord:(NSString *)pass; 3 @end 4 @property (nonatomic,assign) id<GetMessageProtocol> delegate;
//.m
1 if ([self.delegate respondsToSelector:@selector(getNum:withPassWord:)]) { 2 [self.delegate getNum:num.text withPassWord:passWord.text]; 3 } 4 #pragma mark - GetMessageProtocol 5 - (void)getNum:(NSString *)num withPassWord:(NSString *)pass { 6 7 } 8 registerCtrl.delegate = self;
通知 注意postNotificationName 必须一致
1 [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName object:self userInfo:dic]; //dic存放在userinfo中 dic中存放要传过去的值是个字典 2 //接受通知 3 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeAction:) name:NotificationName object:nil];
KVO监听
1 keyPath: 监听的属性名 2 object: 被观察的对象 3 change: 属性值 4 context: 上下设备文 5 6 [registerCtrl addObserver:self forKeyPath:@"属性名称1" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil]; 7 [registerCtrl addObserver:self forKeyPath:@"属性名称2" options:NSKeyValueObservingOptionNew context:nil]; 8 //触发的事件 9 - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { 10 //object的值是registerCtrl 11 if ([keyPath isEqualToString:@"属性名称1"]) { 12 13 }else if ([keyPath isEqualToString:@"属性名称2"]) { 14 15 } 16 }
KVO观察者方法
//.h
@property (nonatomic, copy) NSString *属性名称1; @property (nonatomic, copy) NSString *属性名称2;
//.m 必须通过setter方法改变值或者KVC
KVO方式
1 //触发的事件 2 [indexCollectionView addObserver:self forKeyPath:@"属性名称" options:NSKeyValueObservingOptionNew context:nil]; 3 [posterCollectionView addObserver:self forKeyPath:@"pathIndex" options:NSKeyValueObservingOptionNew context:nil]; 4 - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { 5 //得到改变后的新值 6 NSInteger index = [[change objectForKey:@"new"] integerValue]; 7 8 } 9 }
Block block的返回值 block的名称 block的参数
1 typedef void(^SucccessBlock)(NSString *); //Block的定义 2 @property(nonatomic,copy)SucccessBlock loginBlock; //block的声明 要用copy防止block的循环引用 3 _freindBlcok(friends); block的调用 4 [[MyXMPPManager shareManager] getFreind:^(NSArray *freinds) {} //block的赋值 实现
时间: 2024-10-06 19:18:52