[关闭]
@chenbinghua 2017-04-11T10:39:23.000000Z 字数 2134 阅读 1017

iOS开发之通知、代理、block

iOS笔记


通知三部曲

注册、发送、移除

  1. @implementation ViewController
  2. - (void)viewDidLoad {
  3. [super viewDidLoad];
  4. // 注册通知
  5. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(action:) name:@"NOTIFICATION_NAME" object:nil];
  6. }
  7. - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
  8. // 发送通知
  9. [[NSNotificationCenter defaultCenter] postNotificationName:@"NOTIFICATION_NAME" object:nil userInfo:nil];
  10. }
  11. - (void)action:(NSNotification *)notification {
  12. NSLog(@"通知我啦!");
  13. }
  14. - (void)dealloc{
  15. // 移除通知
  16. [[NSNotificationCenter defaultCenter] removeObserver:self];
  17. }
  18. @end
  1. // 通知的响应事件
  2. - (void)action:(NSNotification *)notif{
  3. }

代理

.h文件

  1. #import <UIKit/UIKit.h>
  2. #import "TiHuoObject.h"
  3. @protocol GDQueRenTiHuoTableViewCDelldelegate<NSObject>
  4. @required
  5. - (void)updatedText:(NSString *)text atIndexPath:(NSIndexPath *)indexPath;
  6. @required
  7. - (void)updatedButton:(BOOL)isSelect atIndexPath:(NSIndexPath *)indexPath;
  8. @end
  9. @interface GDQueRenTiHuoTableViewCell : UITableViewCell
  10. @property (nonatomic,weak) id<GDQueRenTiHuoTableViewCDelldelegate> delegate;
  11. - (void)setData:(NSDictionary *)dic;
  12. - (void)setTihuo:(TiHuoObject *)tihuo;
  13. @end

.m文件

  1. if([self.delegate respondsToSelector:@selector(updatedButton:atIndexPath:)]) {
  2. GDQueRenTiHuoViewController *vc = (GDQueRenTiHuoViewController *)self.delegate;
  3. [self.delegate updatedButton:button.selected atIndexPath:[vc.tableView indexPathForCell:self]];
  4. }
  5. if([self.delegate respondsToSelector:@selector(updatedText:atIndexPath:)]) {
  6. GDQueRenTiHuoViewController *vc = (GDQueRenTiHuoViewController *)self.delegate;
  7. [self.delegate updatedText:textField.text atIndexPath:[vc.tableView indexPathForCell:self]];
  8. }

block

.h文件

  1. #import <UIKit/UIKit.h>
  2. @interface ZSSelectView : UIWindow
  3. typedef void(^ResultBlock)(NSInteger index,NSString *result);
  4. @property (nonatomic,strong) NSArray *contentArray; // 展示数据数组
  5. @property (nonatomic,copy) ResultBlock resultBlock;
  6. - (void)show;
  7. + (instancetype)selectViewWithTitle:(NSString *)title andContentArray:(NSArray *)contentArray andResultBlock:(ResultBlock) resultBlock;
  8. -(void)tap;
  9. @end

.m文件

  1. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
  2. if (_resultBlock) {
  3. _resultBlock(indexPath.row,_contentArray[indexPath.row]);
  4. }
  5. self.hidden = YES;
  6. [self resignKeyWindow];
  7. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注