最近也不知道寫什么好,因為空閑下來就想寫點東西,以前寫代碼沒有注意到代理和block的規(guī)范,最好是帶上當前類,為了提高自己代碼的規(guī)范,就寫了這篇簡單的文章
代理
第一步
在被代理者聲明一個協(xié)議,寫出一個方法
代理的規(guī)范寫法:類名+Delegate
方法的規(guī)范寫法:類名+(第一個參數(shù)是類本身)+(其他參數(shù))
@class FirstView;
@protocol FirstViewDelegate <NSObject>
@optional
- (void)FirstViewbtnClick:(FirstView *)firstView andStr:(NSString *)str;
@end
第二步:
再擁有一個代理屬性
代理使用weak防止循環(huán)引用
使用id 并遵守代理
@property (nonatomic,weak) id <FirstViewDelegate> delegate;
第三步:
在某個事件操作時候,進行查看代理是否遵循代理,如果遵循代理,則讓代理相應協(xié)議中的方法
if (_delegate &&[_delegate respondsToSelector:@selector(FirstViewbtnClick: andStr:)]) {
[_delegate FirstViewbtnClick:self andStr:str];
}
第四步:讓代理者遵循協(xié)議,并且實現(xiàn)協(xié)議方法
@interface ViewController ()<FirstViewDelegate>
//代理
- (void)FirstViewbtnClick:(FirstView *)firstView andStr:(NSString *)str
{
NSLog(@"%@",str);
}
通知
第一步:這里在某個事件被操作時候發(fā)出通知,類似于代理中查看代理者是否遵循代理
[[NSNotificationCenter defaultCenter] postNotificationName:@"selectRow" object:nil userInfo:@{@"selectRowKey":_str}];
第二步:接受通知,這里注意那個方法是需要傳遞參數(shù)的
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ssrpickerselectrow:) name:@"selectRow" object:nil];
第三步:實現(xiàn)接受通知的那個方法,注意這里的key要和發(fā)出通知的一致。建議最好是寫一個單獨的類存放這些東西。我這里為了大家都看得懂就不寫了。
- (void)noti:(NSNotification *)noti
{
NSLog(@"%@",noti.object);
}
第四步:記得移除通知
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
Block
類比代理
第一步:聲明一個block
typedef void(^Block) (FirstView *firstVC, NSString *str);
第二步:擁有一個block屬性
@property (nonatomic,copy) Block block;
第三步:在某個事件操作時候
if (_block) {
_block(self, str);
}
第四步
self.first.block = ^(FirstView *firstVC, NSString *str) {
NSLog(@"%@",str);
};
Demo里面把三種方法都寫齊全了
代碼留給你,喜歡和點贊留給我
https://gitee.com/lanyingwei/codes/jem9ib4vxy2wuopgkalfz91