代理、通知、KVO简介

2016-04-25  本文已影响68人  Mr_董

代理

通知

// 监听键盘通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
//注意要在dealloc中移除通知。如果不移除,当还接受到这个通知时,会调用`self`的对应方法,但self已经销毁,会崩溃。
    [[NSNotificationCenter defaultCenter] removeObserver:self];

代理和通知的区别

代理的写法

#import <UIKit/UIKit.h>

@class DZLoadMoreFooter;

@protocol DZLoadMoreFooterDelegate <NSObject>
@optional
- (void)loadMoreFooterDidClickLoadMoreButton:(DZLoadMoreFooter *)footer;
@end

@interface DZLoadMoreFooter : UIView
+ (instancetype)footer;

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

/**
 * 结束加载状态
 */
- (void)endLoading;

KVC\KVO

// cc监听了aa的name属性的改变
[aa addObserver:cc forKeyPath:@"name" options: NSKeyValueObservingOptionOld context:nil];

// cc得实现监听方法
/**
 * 当监听到object的keyPath属性发生了改变
 */
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    NSLog(@"监听到%@对象的%@属性发生了改变, %@", object, keyPath, change);
}
上一篇下一篇

猜你喜欢

热点阅读