OC基础之选择器的使用

FJAnimal.h

#import <Foundation/Foundation.h>


@interface FJAnimal : NSObject

@property(nonatomic,copy) NSString *name;


/**定义一个动物的父类,属性名字*/

+ (instancetype) animalWithName:(NSString *)name;

/**玩耍*/

- (void) play;

/**吃东西*/

- (void) eat;


@end

FJAnimal.m

@implementation FJAnimal


+ (instancetype)animalWithName:(NSString *)name{

    

    return  [[self alloc]initWithName:name];

}


- (instancetype)initWithName:(NSString *)name{

    if (self = [super init]) {

        _name = name;

    }

    return self;

}


- (void)play{

    NSLog(@"%@正在玩耍!",_name);

}


- (void) eat{

    NSLog(@"%@正在吃东西!",_name);

}


@end

FJCat.h

#import "FJAnimal.h"


@interface FJCat : FJAnimal

/**猫特有的动作:爬树*/

- (void) climbTheTree;



@end

FJCat.m

#import "FJCat.h"


@implementation FJCat



- (void)climbTheTree{

    NSLog(@"%@正在爬树!",self.name);

}

FJDog.h

#import "FJAnimal.h"


@interface FJDog : FJAnimal


/**猫特有的动作看门*/

- (void) keepTheDoor;



@end

FJDog.m

#import "FJDog.h"


@implementation FJDog


- (void)keepTheDoor{

    NSLog(@"%@可以看门",self.name);

}



@end

main.m

#import <Foundation/Foundation.h>

#import "FJCat.h"

#import "FJDog.h"

//通过传入第三个参数,传入一个指向函数的指针让函数中要做的运算不再是程序中的硬代码

// 指向函数的指针实现了代码的解耦合,让函数更加通用

int foo(int *arr,int n,int (*p)(int ,int )){

    int sum = arr[0];

    for(int i=0;i<n;i++){

        sum= p(sum,arr[i]);

    }

    return sum;

}


int add(int a,int b){

    return a+b;

}


int sub(int a,int b){

    return a-b;

}

int mul(int a,int b){

    return a*b;

}

void bar(id obj,SEL sel,id param){

    

    if ([obj respondsToSelector:sel]) {

        

        [obj performSelector:sel withObject:param];

    }

    

}

int main(int argc, const char * argv[]) {

    @autoreleasepool {

        int x[] = {1,2,3,4,5};

        printf("%d\n",foo(x, sizeof x/sizeof x[0], add));

        printf("%d\n",foo(x, sizeof x/sizeof x[0], sub));

        printf("%d\n",foo(x, sizeof x/sizeof x[0], mul));

        

        FJCat *cat = [FJCat animalWithName:@"cat"];

        FJDog *dog = [FJDog animalWithName:@"dog"];

        bar(cat, @selector(climbTheTree), nil);

        bar(dog, @selector(keepTheDoor), nil);

        

    }

    return 0;

}


你可能感兴趣的:(OC选择器)