黑马程序员 block,protocol

时间:2014-05-08 17:40:55   收藏:0   阅读:225

#import <Foundation/Foundation.h>

  // 利用typedef创建block

 typedef int (^MyBlock) (int,int);

  // <>表示遵守协议

@protocol MyProtocol <NSObejct>

  /*

    1.reqiured:要求实现方法,不实现方法编译器会发出警告

    2.optional:不要求实现方法

    3.默认情况下为reqiured

    4.协议之间可以相互遵守,一个协议可以遵守多个协议<....,....,....>

    5.一个类也可以遵守多个协议<....,....,....>

    */

  -(void)tset1;

   @reqiured

  -(void)test2;

  -(void)test3;

   @optional

  -(void)test4;

@end

// 代表Person类遵守协议,可以使用协议里的所有方法声明

@interface Person : NSObject <MyProtocol>

// 调用这个id必须遵守MyProtocol这个协议

@proterty (nonatomic, retain) id <MyProtocol> car;

@end

@implementation Person

  // 要求实现

 - (void)test1

  {

     NSSLog(@"test1实现!");

  }

 - (void)test2

  {

     NSSLog(@"test2实现!");

  }

 - (void)test3

  {

     NSSLog(@"test3实现!");

  }

- (void)test4

  {

    

  }

@end

@interface Car : NSObject <MyProtocol>

@end

@implementation Car

@end

@interface Book : NSObject

@end

@implementation Book

@end

int main()

{

     // block代码的书写规范

    MyBlock sumBlock = ^(int a, int b)

      {

          return a+b;

      }

     NSLog(@"%d",sumBlock(10, 15));

    Person *p = [[Person alloc] init];

    Car *car1 = [[Car alloc] init];

    // Car必须遵守MyProtocol协议才能赋给_car

    p.car = car1;

    return 0;

}

黑马程序员 block,protocol,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!