您的位置:首页 > 移动开发 > IOS开发

iOS block 代理 通知方法总结

2017-03-28 18:11 344 查看
一.block

先声明block

<1>声明block
typedef void(^myBlock)(NSString *name);

//<2>声明一个block属性
@property (nonatomic,
copy) myBlock block;
 //<3>调用block、传值    
    if (self.block) {
        self.block(@"123");
    }
  //<4>实现block
    //a:NSString *name  
代表传过来的值
    next.block = ^(NSString *name){
        //<5>实现
        NSLog(@"%@",name);
        self.view.backgroundColor = [UIColor
cyanColor];
    };
二.代理

@protocol NextViewControllerDelegate <NSObject>
-(void)nextViewControllerSendData;
@end

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

if ([self.delegate respondsToSelector:@selector(nextViewControllerSendData)]) {
        //代理有实现方法
        [self.delegate nextViewControllerSendData];
    }
//遵守协议

@interface ViewController ()<NextViewControllerDelegate>

next.delegate = self;
-(void)nextViewControllerSendData{

    NSLog(@"nextViewControllerSendData");
}
三通知
//1.发送通知

[[NSNotificationCenter
defaultCenter]postNotificationName:@"notification"
object:nil
userInfo:@{@"key":[NSString
stringWithFormat:@"%ld",_number]}];
//2.接收通知

[[NSNotificationCenter
defaultCenter] addObserver:self
selector:@selector(addNumber:)
name:@"notification"
object:nil];
- (void)addNumber:(NSNotification *)noti
{
    UILabel * label = (id)[self.view
viewWithTag:10];
    label.text = [NSString
stringWithFormat:@"%@",[noti.userInfo
objectForKey:@"key"]];   
}
// 3.根据观察者
移除所有通知

    [[NSNotificationCenter
defaultCenter] removeObserver:self];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: