1. 程式人生 > >代理、block、通知中心傳值

代理、block、通知中心傳值

1.代理
委託者.h檔案

@protocol DBDoorHoneListTabCollectionCellDelegate <NSObject>
- (void)selectedItemButton:(NSInteger)index;

@end

@interface DBDoorHoneListTabCollectionCell : UITableViewCell
@property(nonatomic,weak)id<DBDoorHoneListTabCollectionCellDelegate>   DBDoorHoneListTabCollectionCellDelegate;

@end
委託者.m檔案
if(self.DBDoorHoneListTabCollectionCellDelegate&&[self.DBDoorHoneListTabCollectionCellDelegate respondsToSelector:@selector(selectedItemButton:)]) {
       [self.DBDoorHoneListTabCollectionCellDelegate selectedItemButton:indexPath.row];

}

代理控制器.m

 listColCell.DBDoorHoneListTabCollectionCellDelegate = self;
 - (void)selectedItemButton:(NSInteger)index
{
    doorRow = index;
}


2.block


宣告.h
 

typedef void (^ReturnTextBlock)(NSString *showText);//給block重新命名,方便呼叫
@interface B : UIViewController
@property (nonatomic, copy) ReturnTextBlock returnTextBlock;//宣告一個block屬性
- (void)returnText:(ReturnTextBlock)block;//加上後方便第A檢視書寫該block方法

宣告.m
- (void)returnText:(ReturnTextBlock)block {
self.returnTextBlock = block;

}
 if (self.returnTextBlock != nil) {
self.returnTextBlock(self.inputTF.text);


呼叫.m

[bVC returnText:^(NSString *showText) {
    self.showLabel.text = showText;
}];

 

3.通知中心
 [[NSNotificationCenter  defaultCenter]postNotificationName:@"currentItemIndex" object:@(index)];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(currentItemIndex:) name:@"currentItemIndex" object:nil];

-(void )currentItemIndex:(NSNotification*)not{
     NSInteger deviceId = [not.object integerValue];

}