天天看点

1类之间通信的常用方法Block、Notification、Delegate

下面分别从Java OC Swift三个方面比较三种语言的异同

OC:Block

//宏定义

-(void)blockTest{

   MyBlock myblock01 = ^(int a){

       NSLog(@"参数:%d",a);

       return 20;

    };

   NSLog(@"返回值:%d",myblock01(101));

    [selftestBlock:myblock01];

    [selftestBlockNew:^(int a){

        NSLog(@"内部定义Block");

    }];

}

//内部调用

-(void)blockTest1{

    //声明一个block变量

   void(^myBlock)();

   __block int a =3;

    myBlock = ^(){

       NSLog(@"参数:%d",a);

    };

    myBlock();

}

//Block 作为参数

- (void)testBlock:(MyBlock)myBlock {

    myBlock(10);

}

- (void)testBlockNew:(MyBlockNew)myBlock {

    myBlock(10);

}

一般作为参数传递是不带返回值的。

OC:Notification

-(void)notificationTest{

//    注册广播

    [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(weekNotification:)name:@"notificationName"object:nil];

//   发送广播

    NSDictionary *dic = [[NSDictionaryalloc]initWithObjectsAndKeys:@"123",@"456"];

    [[NSNotificationCenterdefaultCenter]postNotificationName:@"notificationName"object:[NSNumbernumberWithInteger:5]userInfo:dic];

}

//   响应广播

- (void)weekNotification:(NSNotification *)notification {

   NSNumber *num = notification.object;

   NSDictionary *dic = notification.userInfo;

}

OC:Delegate

-(void)protocol{

    secondClass *sc = [[secondClassalloc]init];

    sc.delegate =self;

    [sc secondmethod];

}

//代理方法

-(void)protocolTest{

   NSLog(@"代理方法");

}

然后在另一个文件的h中定义

@protocol protocolName

@optional

-(void)protocolTest;

@end

@interface secondClass :NSObject

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

m文件中做如下定义

[self.delegateprotocolTest];

Swift:Block

//  Block

   func blockTest(){

        var sc:secondClass =secondClass()

        sc.secondBlock(1){ (success) ->()in

            println("this is Block")

        }

       var blo:blockTestA = { (success) ->()in

            println("this is BlockAAA")

        }

        sc.secondBlock(2, block: blo)

    }

Swift:Notification

//  注册广播

   func notificationTest(){

       NSNotificationCenter.defaultCenter().addObserver(self, selector:"weekNotification:", name: "notificationName", object: nil)

       var x:Float =1.9

       var dic:[String:String] = ["123":"456"]

       NSNotificationCenter.defaultCenter().postNotificationName("notificationName", object: x, userInfo: dic)

    }

//   响应广播

   func weekNotification(notification:NSNotification){

       var num:Float = notification.objectasFloat

       var dic:Dictionary = notification.userInfo!asDictionary

       var str:String =  dic["123"]asString

       println("\(str)")

    }

Swift:Delegate

//  代理测试代码 需要继承(:协议名)

   func delTestMethod(){

        var sc:secondClass =secondClass()

        sc.delegate =self

        sc.secondMethod()

    }

//  代理方法

   func delTest(){

       println("delegate")

    }

另一个文件做如下定义

    var delegate:pieTapDesDelegate?

   func secondMethod(){

       delegate?.delTest()

    }