Student.h:

#import <Foundation/Foundation.h>
@protocol Study,Learn;
@interface Student : NSObject<Study,Learn>

@end



Student.m:

#import "Student.h"
#import "Study.h"
#import "Learn.h"
@implementation Student

@end


Study.h:

#import <Foundation/Foundation.h>

@protocol Study <NSObject>
//@required表示必须实现
//随便字面上说是必须实现,但是编译器并不强求实现
@required
-(void)test1;
-(void)test2;
//@optional表示可选(可实现,也可以不实现)
@optional
-(void)test3;
@end



Learn.h:

#import <Foundation/Foundation.h>

@protocol Learn <NSObject>

@end



main:

#import <Foundation/Foundation.h>
#import "Student.h"
#import "Learn.h"

@protocol Study;

int sum(int a,int b){
    return a+b;
}

void test(){
    //调用block方法求和
    int c=sum(10,10);
    NSLog(@"调用block方法求和:%i",c);
}

void test1(){
    //定义了Sum这种block类型
    typedef int (^Sum1) (int,int);
    //定义了SumP这种指针类型,指向函数的
    typedef int (*SumP) (int,int);
    //定义了一个sum的Block变量
    Sum1 Sum12=^(int a,int b){
        return a+b;
    };
    int s=Sum12(10,10);
    NSLog(@"sum:%i",s);
    //因为宏定义的时候已经包含了*,所以在定义变量的时候不需要加*了
    SumP p=sum;
    //int j=(*p)(20,30);
    int j=p(20,30);
    NSLog(@"函数sum:%i",j);
}
int main(int argc, const char * argv[])
{

    @autoreleasepool {
        
        Student *stu=[[[Student alloc] init] autorelease];
        //conformsToProtocol:判断是否遵守了协议
        if([stu conformsToProtocol:@protocol(Study)])
        {
            NSLog(@"遵守了Study协议");
        }
        //respondsToSelector:判断是否实现了某一方法
        if(![stu respondsToSelector:@selector(test)])
        {
            NSLog(@"Student没有实现这个方法");
        }

        //block的实现,block跟函数调用差不多,但block可以写在任何地方,函数不能写在函数内部,block跟指向函数的指针用法一样
        int (^Sum)(int,int)=^(int a,int b){
            return a+b;
        };
        //调用block方法求和
        int c=Sum(10,10);
        NSLog(@"调用block方法求和:%i",c);
        //调用函数方法求和
        int d=sum(11, 11);
        NSLog(@"调用函数方法求和:%i",d);
        //调用函数指针的方法求和,定义一个指针指向一个函数
        int(*sumP)(int,int)=sum;
        //(*sump)代表指向的函数
        int i=(*sumP)(22,22);
        NSLog(@"调用指向函数的指针的方法来求和:%i",i);

        NSLog(@"******************************************");
       test1();
    }
    return 0;
}



结果:

2013-08-02 14:53:13.490 Protocol Block 成员变量补充[713:303] 遵守了Study协议

2013-08-02 14:53:13.491 Protocol Block 成员变量补充[713:303] Student没有实现这个方法

2013-08-02 14:53:13.492 Protocol Block 成员变量补充[713:303] 调用block方法求和:20

2013-08-02 14:53:13.493 Protocol Block 成员变量补充[713:303] 调用函数方法求和:22

2013-08-02 14:53:13.493 Protocol Block 成员变量补充[713:303] 调用指向函数的指针的方法来求和:44

2013-08-02 14:53:13.493 Protocol Block 成员变量补充[713:303] ******************************************

2013-08-02 14:53:13.494 Protocol Block 成员变量补充[713:303] sum:20

2013-08-02 14:53:13.494 Protocol Block 成员变量补充[713:303] 函数sum:50