天天看點

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()

    }