常用设计模式
通知 NSNotification
通知由消息中心发送
消息中心在整个工程中有且只有一个
消息中心可以发送多条消息 可以在工程中的任何位置接收消息 通过消息的名称区分消息
消息的名字是消息的唯一标识
1>为消息中心添加观察者
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeMusicName:) name:@"musicName" object:nil];
2>实现selector方法
- (void)changeMusicName:(NSNotification *)notification{
//获取消息携带的内容
NSString * string = notification.object;
//或者使用
//NSString * string = notification.userInfo;
}
3>消息中心发送消息
[[NSNotificationCenter defaultCenter]postNotificationName:@"musicName" object:string userInfo:nil];
KVC
KVC 替代代理的优点 不需要设置协议 不需要设置代理 不需要遵守协议 不需要实现协议中的方法 直接使用setValue:forKey:直接赋值
1>A->B
//使用KVC向第二个界面传值(第二个页面含有color/delegate属性)
[nvc setValue:[UIColor blueColor] forKey:@"color"];
[nvc setValue:self forKey:@"delegate"];
KVO
KVO是 key - value - observer 的缩写 键值观察者的简称
主要用来观察成员变量的值的变化
如果成员变量的值发生改变 就会立即出发KVO的方法
在真正的开发使用范围 :当下载一款app的时候 第一次打开需从服务器获取数据并存放在本地内存中 第二次代开应用的时候 需要将本地的数据与服务器上的数据做比较 如果发生改变 需要从服务器上重新获取 如果没有改变直接将本地内存中存放的数据 显示在UI上 这样能够节省时间
/**
- 1.添加观察者对象 用哪个类的对象观察成员变量的变化 这个位置就写哪个类的对象指针 通常为self
2.被观察的成员变量的名称
3.被观察的成员变量 变化前的值 或 变化后的值- 上下文 默认是nil
/
1>[boy addObserver:self forKeyPath:@"boyName" options:NSKeyValueObservingOptionNew |NSKeyValueObservingOptionOld context:nil];
/*
- 上下文 默认是nil
- 只要被观察的成员变量的值发生改变 就会触发下面的方法
- @param keyPath 被观察的对象的成员变量
- @param object 被观察的对象
- @param change 成员变量变化前和变化后的值(变化前 的值 对应的键是old 变化后对应的键是new)
- @param didReceiveMemoryWarning
*/
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
if ([object isKindOfClass:[Boy class]]) {
UITextField * field = (UITextField *)[self.view viewWithTag:0];
NSString * old = change[@"old"];
NSString * new = change[@"new"];
field.text = [NSString stringWithFormat:@" old:%@ , new: %@",old,new];
}
UITextField * field = (UITextField *)[self.view viewWithTag:1];
NSString * old = change[@"old"];
NSString * new = change[@"new"];
field.text = [NSString stringWithFormat:@" old:%@ , new: %@",old,new];
}
协议代理 B—>A传值 B为协议方A为代理方
1.确定协议方和代理方
2.协议方定义协议和代理
@protocol sendInfoWithBtnTitle <NSObject>
-(void)sendInfo:(NSString *)title;
@end
@property(nonatomic,assign) id<sendInfoWithBtnTitle> delegate;
//代理方法是否实现
if ([self.delegate respondsToSelector:@selector(sendInfo:)])
{
[self.delegate sendInfo:((UIButton *)sender).currentTitle];
}
else
{
NSLog(@"被动方没有实现协议中的方法或者没有设置代理");
}
3.代理方遵守协议并实现协议方法
@interface ViewController ()<sendInfoWithBtnTitle>
//协议方法
-(void)sendInfo:(NSString *)title
{
self.navigationItem.title = title;
}