iOS之单例,代理,通知,KVO,Block全能解析

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

//单例//.h+ (Instannce *)shareInstance;//.mstaticInstannce *instance =nil;@implementationInstannce//定义一个创建单例对象的方法+ (Instannce *)shareInstance {if(instance ==nil) {

instance=[[Instannce alloc] init];

}returninstance;

}//使用alloc的时候调用的方法instancetype+ (id)allocWithZone:(struct_NSZone *)zone {if(instance ==nil) {

instance=[super allocWithZone:zone];

}returninstance;

}- (id)copy {returnself;

}- (id)retain {returnself;

}-(NSUInteger)retainCount {//返回无符号最大值returnUINT_MAX;

}- (onewayvoid)release {//什么也不做}//代理//.h@PRotocolGetMessageProtocol <NSObject >

- (void)getNum:(NSString *)num withPassWord:(NSString *)pass;@end@property (nonatomic,assign)id<GetMessageProtocol>delegate;//.mif([self.delegaterespondsToSelector:@selector(getNum:withPassWord:)]) {

[self.delegategetNum:num.text withPassWord:passWord.text];

}#pragmamark - GetMessageProtocol

- (void)getNum:(NSString *)num withPassWord:(NSString *)pass {

}

registerCtrl.delegate=self;//通知 注意postNotificationName 必须一致[[NSNotificationCenter defaultCenter] postNotificationName:NotificationNameobject:self userInfo:dic];//dic存放在userinfo中 dic中存放要传过去的值是个字典//接受通知[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeAction:) name:NotificationNameobject:nil];//KVO监听/*KVO观察者方法

keyPath: 监听的属性名

object: 被观察的对象

change: 属性值

context: 上下设备文*/[registerCtrl addObserver:self forKeyPath:@"属性名称1"options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:nil];

[registerCtrl addObserver:self forKeyPath:@"属性名称2"options:NSKeyValueObservingOptionNew context:nil];//触发的事件- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)objectchange:(NSDictionary *)change context:(void*)context {//object的值是registerCtrlif([keyPath isEqualToString:@"属性名称1"]) {

}elseif([keyPath isEqualToString:@"属性名称2"]) {

}

}//.h@property (nonatomic, copy) NSString *属性名称1;

@property (nonatomic, copy) NSString*属性名称2;//.m 必须通过setter方法改变值或者KVC//KVO方式//触发的事件[indexCollectionView addObserver:self forKeyPath:@"属性名称"options:NSKeyValueObservingOptionNew context:nil];

[posterCollectionView addObserver:self forKeyPath:@"pathIndex"options:NSKeyValueObservingOptionNew context:nil];- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)objectchange:(NSDictionary *)change context:(void*)context {//得到改变后的新值NSInteger index = [[change objectForKey:@"new"] integerValue];

}

}//Block block的返回值 block的名称 block的参数typedefvoid(^SucccessBlock)(NSString *);//Block的定义@property(nonatomic,copy)SucccessBlock loginBlock;//block的声明 要用copy防止block的循环引用_freindBlcok(friends); block的调用

[[MyXMPPManager shareManager] getFreind:^(NSArray *freinds) {}//block的赋值 实现

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航