基础 (二十) : 通知/代理

通知中心(NSNotificationCenter)

1.png

通知(NSNotification)

一个完整的通知一般包含3个属性:(注意顺序)

  • (NSString*)name; 通知的名称

  • (id)object; 通知发布者(是谁要发布通知)

  • (NSDictionary *)userInfo; 一些额外的信息(通知发布者传递给通知接收者的信息内容)

初始化(可以理解为创建)一个通知(NSNotification)对象

只有通知的的名称和通知的发布者

+(instancetype)notificationWithName:(NSString *)aName object:(id)anObject;

+(instancetype)notificationWithName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo;

  • (instancetype)initWithName:(NSString *)name object:(id)object
    userInfo:(NSDictionary *)userInfo;

发布通知

通知中心(NSNotificationCenter)提供了相应的方法来帮助发布通知

-(void)postNotification:(NSNotification *)notification;

发布一个notification通知,可在notification对象中设置通知的名称、通知发布者、额外信息等

-(void)postNotificationName:(NSString *)aName object:(id)anObject;

发布一个名称为aName的通知,anObject为这个通知的发布者

-(void)postNotificationName:(NSString *)aName object:(id)anObject
userInfo:(NSDictionary *)aUserInfo;

发布一个名称为aName的通知,anObject为这个通知的发布者,aUserInfo为额外信息

1.开始监听意思是(当Bob监听到了baby2发出的娱乐的通知,就会调用eat这个方法)

[[NSNotificationCenter defaultCenter] addObserver:Bob selector:@selector(eat:) name:@"娱乐" object:baby2];
 2.创建通知(baby2创建了一个叫娱乐的通知,并设置了通知的内容)

NSNotification*note = [NSNotification notificationWithName:@"娱乐" object:baby2 userInfo:@{@"通知的key":@"通知的value"}];

 3.发布通知(三部曲)

[[NSNotificationCenter defaultCenter] postNotification:note];

 第二种简写方式


[[NSNotificationCenter defaultCenter] addObserver:baby selector:@selector(eat:) name:@"通知的名称" object:baby2];

[[NSNotificationCenter

defaultCenter] postNotificationName:@"通知的名称"
object:baby2 userInfo:@{@"通知的key":@"通知的value"}];

注册通知监听器

通知中心(NSNotificationCenter)提供了方法来注册一个监听通知的监听器(Observer)

-(void)addObserver:(id)observer
selector:(SEL)aSelector name:(NSString *)aName object:(id)anObject;

observer:监听器,即谁要接收这个通知

aSelector:收到通知后,回调监听器的这个方法,并且把通知对象当做参数传入

aName:通知的名称。如果为nil,那么无论通知的名称是什么,监听器都能收到这个通知

anObject:通知发布者。如果为anObject和aName都为nil,监听器都收到所有的通知

-(id)addObserverForName:(NSString *)name object:(id)obj
queue:(NSOperationQueue *)queue usingBlock:(void (^)(NSNotification
*note))block;

name:通知的名称

obj:通知发布者

block:收到对应的通知时,会回调这个block

queue:决定了block在哪个操作队列中执行,如果传nil,默认在当前操作队列中同步执行

取消注册通知监听器

通知中心不会保留(retain)监听器对象,在通知中心注册过的对象,必须在该对象释放前取消注册。否则,当相应的通知再次出现时,通知中心仍然会向该监听器发送消息。因为相应的监听器对象已经被释放了,所以可能会导致应用崩溃

通知中心提供了相应的方法来取消注册监听器

-(void)removeObserver:(id)observer;

-(void)removeObserver:(id)observer name:(NSString
*)aName object:(id)anObject;

一般在监听器销毁之前取消注册(如在监听器中加入下列代码):

-(void)dealloc {

[super dealloc]; 非ARC中需要调用此句

[[NSNotificationCenter defaultCenter] removeObserver:self];

}

UIDevice通知

UIDevice类提供了一个单粒对象,它代表着设备,通过它可以获得一些设备相关的信息,比如电池电量值(batteryLevel)、电池状态(batteryState)、设备的类型(model,比如iPod、iPhone等)、设备的系统(systemVersion)

通过[UIDevice currentDevice]可以获取这个单粒对象(一般用来做系统适配)

UIDevice对象会不间断地发布一些通知,下列是UIDevice对象所发布通知的名称常量:

UIDeviceOrientationDidChangeNotification 设备旋转

UIDeviceBatteryStateDidChangeNotification 电池状态改变

UIDeviceBatteryLevelDidChangeNotification 电池电量改变

UIDeviceProximityStateDidChangeNotification 近距离传感器(比如设备贴近了使用者的脸部)

键盘通知

我们经常需要在键盘弹出或者隐藏的时候做一些特定的操作,因此需要监听键盘的状态

键盘状态改变的时候,系统会发出一些特定的通知

UIKeyboardWillShowNotification 键盘即将显示

UIKeyboardDidShowNotification 键盘显示完毕

UIKeyboardWillHideNotification 键盘即将隐藏

UIKeyboardDidHideNotification 键盘隐藏完毕

UIKeyboardWillChangeFrameNotification 键盘的位置尺寸即将发生改变

UIKeyboardDidChangeFrameNotification 键盘的位置尺寸改变完毕

系统发出键盘通知时,会附带一下跟键盘有关的额外信息(字典),字典常见的key如下:

UIKeyboardFrameBeginUserInfoKey 键盘刚开始的frame

UIKeyboardFrameEndUserInfoKey 键盘最终的frame(动画执行完毕后)

UIKeyboardAnimationDurationUserInfoKey 键盘动画的时间

UIKeyboardAnimationCurveUserInfoKey 键盘动画的执行节奏(快慢)

  • (void)viewDidLoad {

    [super viewDidLoad];

    // 即将显示的键盘

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:)
    name:UIKeyboardWillShowNotification object:nil];

    // 即将推出的键盘

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

}

/**

  • 监听键盘的即将显示

*/

  • (void)keyboardWillShow:(NSNotification *)note
    {

// 获得键盘的frame

CGRectframe = [note.userInfo[UIKeyboardFrameBeginUserInfoKey] CGRectValue];

// 修改底部约束

self.bottn.constant= frame.size.height;

执行动画

CGFloatduration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];

[UIView animateWithDuration:duration animations:^{

    [self.view layoutIfNeeded];
}];

}

/**

  • 监听键盘的即将隐藏

*/

  • (void)keyboardWillHide:(NSNotification *)note

{

// 修改底部约束

self.bottn.constant= 0;

// 执行动画

CGFloatduration = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];

[UIView animateWithDuration:duration animations:^{

    [self.view layoutIfNeeded];

}];

}

  • (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event

{

// 文本框不再是第一响应者,就会退出键盘

[self.textField resignFirstResponder];

[self.textField endEditing:YES];

[self.view endEditing:YES];

}

注意:监听键盘的显示和隐藏,最重要的思想就是拿整个view的高度减去键盘的高度,注意细节

通知和代理的选择

共同点

利用通知和代理都能完成对象之间的通信

(比如A对象告诉D对象发生了什么事情, A对象传递数据给D对象)

不同点

代理 :一对一关系(1个对象只能告诉另1个对象发生了什么事情)

通知
:
多对多关系(1个对象能告诉N个对象发生了什么事情, 1个对象能得知N个对象发生了什么事情)

****************************************************************************************************************************************笔记**********************************************

框架搭建

框架搭建

  • 1.操作storyboard(toolBar+tableView)
  • 2.添加资料(plist,图片,MJExtension)
  • 3.创建对应模型/cell(xib注册)

  • 4.完善vc.m中的代码(lazy

  • dataSouce + MJExtension)
  • (NSArray *)wines

{

if (!_wines) {

   替换key

[XMGWine setupReplacedKeyFromPropertyName:^NSDictionary *{

  return @{@"imaStr": @"image"};

}];

     plist->模型数组

_wines = [XMGWine objectArrayWithFilename:@"wines.plist"];

}

return _wines;

}

  • 5.cell的完善.(子控件,响应事件)
  • 先禁止文本框的交互

pragma mark - cell自定义

  • (void)setWine:(XMGWine *)wine

{

_wine = wine;

self.icon_Ima.image = wine.icon;

self.name_Lab.text = wine.name;

self.money_Lab.text = wine.money;

self.buyCount_TF.text = [NSString stringWithFormat:@"%ld",
wine.buyCount];

}

  • (instancetype)cellWithTableView:(UITableView *)tableView

{

static NSString *identifier =nil;

if (identifier == nil)

{

identifier = [NSString stringWithFormat:@"%@ID", NSStringFromClass(self)];

[tableView registerNib:[UINib nibWithNibName:NSStringFromClass(self) bundle:nil]
forCellReuseIdentifier:identifier];

}

id cell = [tableView dequeueReusableCellWithIdentifier:identifier];

return cell;

}

customBtn

customBtn

IB_DESIGNABLE的宏的功能就是让XCode动态渲染出该类图形化界面。

IB_DESIGNABLE

@interface XMGCircleBtn ()

IBInspectable 让支持KVC的属性能够在Attribute Inspector中配置。

@property (nonatomic, assign) IBInspectable CGFloat cornerRadius; /**< 圆角 */

@property (nonatomic, assign) IBInspectable CGFloat borderWidth; /**< 边框宽 */

@property (nonatomic, strong) IBInspectable UIColor borderColor; /*< 边框颜色 */

@end

如果造成UI卡顿,记得写这两行代码

self.layer.shouldRasterize =YES;

self.layer.rasterizationScale =YES;

NSNotification

NSNotification

实例中的用法

先定义通知宏(const常量字符串)

  • 命名规范:所在类+触发发送的行为+Notification

define XMGWineCellPlusOnClickNotification @"XMGWineCellPlusOnClickNotification"

define XMGWineCellMinusOnClickNotification @"XMGWineCellMinusOnClickNotification"

define XMGWineCellMinusWine @"XMGWineCellMinusWine"

发送通知

  • 通知的发送一般都有触发条件,比如按钮的点击

减号按钮点击发出的通知

[[NSNotificationCenter
defaultCenter] postNotificationName:XMGWineCellMinusOnClickNotification object:nil userInfo:@{XMGWineCellMinusWine:self.wine}];

加号按钮点击发出的通知

[[NSNotificationCenter
defaultCenter] postNotificationName:XMGWineCellPlusOnClickNotification object:self];

添加通知监听

  • 一般是在控制器的viewDidLoad/viewDidAppear等方法中/或者自定义view的initWithFrame/Corder方法中添加
  • (void)viewDidLoad {

    [super viewDidLoad];

 让控制器成为监听者

[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(cellPlusBtnOnClick:)
name:XMGWineCellPlusOnClickNotification object:nil];

[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(cellMinusBtnOnClick:)
name:XMGWineCellMinusOnClickNotification object:nil];

}

监听者接收通知后调用方法

  • 在收到通知后才会触发调用

pragma
mark - NotificationSEL

  • (void)cellPlusBtnOnClick:(NSNotification *)note

{

[self.tableView reloadData];

XMGWine

*wine = [(XMGWineCell *)note.object wine];

 如果不包含这个模型先添加进来

if (![self.winesInCar
containsObject:wine]) {

[self.winesInCar addObject:wine];

}



 计算应该显示的总价格

CGFloat

totalMoney = self.totalMoney_Label.text.doubleValue;

totalMoney += wine.money.doubleValue;

self.totalMoney_Label.text = [NSString
stringWithFormat:@"%.1f",
totalMoney];

}

  • (void)cellMinusBtnOnClick:(NSNotification *)note

{

[self.tableView reloadData];

XMGWine

*wine = note.userInfo[XMGWineCellMinusWine];

 如果购物车模型中的购买数量是0,那就移除

if (wine.count == 0 && [self.winesInCar containsObject:wine]) {

[self.winesInCar removeObject:wine];

}



 计算应该显示的总价格

CGFloat

totalMoney = self.totalMoney_Label.text.doubleValue;

totalMoney -= wine.money.doubleValue;

self.totalMoney_Label.text = [NSString
stringWithFormat:@"%.1f",
totalMoney];

}

移除监听者

  • 有添加必须以后移除

有添加就需要移除

  • (void)dealloc

{

[[NSNotificationCenter defaultCenter] removeObserver:self];

}

系统自带通知的用法

  • 只监听移除即可
  • 例如cell中监听文本框文字变化
  • (void)awakeFromNib {

    Initialization code

[[NSNotificationCenter defaultCenter] addObserver:self
让cell监听通知

selector:@selector(textChange:)  收到通知后调用的方法

name:UITextFieldTextDidChangeNotification  通知的名称

object:self.buyCount_TF];
发出通知的对象

}

文字改变的通知

  • (void)textChange:(NSNotification *)note {

    NSLog(@"%s, line = %d, note = %@",FUNCTION, LINE, note);

    此处只是演示作用,具体

    1.拦截判断

 2.改变总价格



 根据当前模型中的buyCount与当前值对比,调用相应次数的代理方法

}

  • (void)dealloc

{

[[NSNotificationCenter defaultCenter] removeObserver:self];

}

Delegate

delegate

代理的使用步骤

  • 定义一份代理协议

  • 协议名字的格式一般是:类名+ Delegate

  • 比如UITableViewDelegate

  • 代理方法细节

  • 一般都是@optional

  • 方法名一般都以类名开头

  • 比如-
    (void)scrollViewDidScroll:

  • 一般都需要将对象本身传出去

  • 比如tableView的方法都会把tableView本身传出去

  • 必须要遵守NSObject协议

  • 比如@protocol
    XMGWineCellDelegate <NSObject>

  • 声明一个代理属性

  • 代理的类型格式:id<协议>
    delegate

@property (nonatomic,
weak) id<XMGWineCellDelegate>
delegate;

  • 设置代理对象

xxx.delegate = yyy;

  • 代理对象遵守协议,实现协议里面相应的方法

参考tableView的delegate三大步骤

  • 当控件内部发生了一些事情,就可以调用代理的代理方法通知代理

  • 如果代理方法是@optional,那么需要判断方法是否有实现

if ([self.delegate
respondsToSelector:@selector(wineCell:didClicked:)])
{

[self.delegate wineCell:self

didClicked:XMGWineCellCalculatTypeMinus];

}

iOS监听某些事件的方法

  • 通知(NSNotificationCenter\NSNotification)

  • 任何对象之间都可以传递消息

  • 使用范围

  • 1个对象可以发通知给N个对象

  • 1个对象可以接受N个对象发出的通知

  • 必须得保证通知的名字在发出和监听时是一致的

  • KVO

  • 仅仅是能监听对象属性的改变(灵活度不如通知和代理)

  • 代理

  • 使用范围

  • 1个对象只能设置一个代理(假设这个对象只有1个代理属性)

  • 1个对象能成为多个对象的代理

  • 通知规范

  • 建议使用优先级代理->通知

UIAlertController

UIAlertController

  • 来源于UIAlertView/UIActionSheet
  • (void)testAlert {

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"alert"

          message:@"UIAlertView is deprecated. Use UIAlertController

with a preferredStyle of UIAlertControllerStyleAlert instea"

delegate:self

cancelButtonTitle:@"取消"

otherButtonTitles:@"确定", nil];

[alert

show];

}

pragma
mark - UIAlertViewDelegate

  • (void)alertView:(UIAlertView *)alertView
    clickedButtonAtIndex:(NSInteger)buttonIndex

{

 根据buttonIndex判断是哪个按钮点击了

}

  • 不必再设置代理
  • (void)testAlertController {
 是用来替代UIAlertView/UIActionSheet

 1.创建提示框

UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"alertController" 标题

message:@"描述~"

preferredStyle:UIAlertControllerStyleAlert]; alert/actionSheet

 2.添加按钮和响应事件

 2.1 创建

UIAlertAction *action0 = [UIAlertAction actionWithTitle:@"I know" 按钮文字

style:UIAlertActionStyleCancel 按钮样式

handler:^(UIAlertAction *action) {  按钮响应事件

NSLog(@"%s, line = %d",__FUNCTION__, __LINE__);

}];

 2.2 添加到提示框上

[alert

addAction:action0];

 3.展示提示框

[self presentViewController:alert animated:YES completion:nil];

}

  • 注意文本框只能添加到Alert格式上

keyBoardEditing(键盘处理):

keyBoardEditing

pragma mark - 键盘处理

  • (void)viewDidLoad {

    [super viewDidLoad];

self.tableView.rowHeight = 80;

 监听键盘的frame变化

[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardTransform:)
name:UIKeyboardWillChangeFrameNotification object:nil];

}

通知响应的方法

  • (void)keyboardTransform:(NSNotification *)note

{

NSLog(@"%s, line = %d, %@",__FUNCTION__, __LINE__, note.userInfo);

/*

 打印的note.userInfo

UIKeyboardAnimationCurveUserInfoKey = 7;

UIKeyboardAnimationDurationUserInfoKey = "0.25";

UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 216}}";

UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 775}";

UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 559}";

UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375,
216}}";

UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 451}, {375,
216}}";

*/

 拿到键盘弹出时间

CGFloat

animaDur = [note.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];

 拿到键盘将要变化的y值

CGFloat

keyboardY = [note.userInfo[UIKeyboardFrameEndUserInfoKey]
CGRectValue].origin.y;

 计算出约束变化的值

CGFloat

bottomMargin = CGRectGetHeight([UIScreen mainScreen].bounds) - keyboardY;

self.bottomMar_Con.constant = bottomMargin;

 动画布局完成操作

[UIView

animateWithDuration:animaDur animations:^{

[self.view layoutIfNeeded];

}];

}

有添加就有移除

  • (void)dealloc

{

[[NSNotificationCenter defaultCenter] removeObserver:self];

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335

推荐阅读更多精彩内容