SEL selector选择器
2015-12-24 16:36 AB小博客 阅读(273) 评论(0) 编辑 收藏 举报// // main.m // Selector // // Created by MAC on 15/12/24. // Copyright © 2015年 MAC. All rights reserved. // #import <Foundation/Foundation.h> #import "Demo.h" #import "Dog.h" #import "Animal.h" #import "Person.h" #import "Cat.h" int main(int argc, const char * argv[]) { @autoreleasepool { Demo *D = [[Demo alloc]init]; [D method1]; [D executeSelector]; Person *p1 = [[Person alloc]init]; Dog *d = [[Dog alloc]init]; Cat *c = [[Cat alloc]init]; [p1 care:d]; [p1 care:c]; } return 0; }
// // Demo.h // Selector // // Created by MAC on 15/12/24. // Copyright © 2015年 MAC. All rights reserved. // #import <Foundation/Foundation.h> @interface Demo : NSObject -(void)method1; -(void)method2; -(void)executeSelector; @end // // Demo.m // Selector // // Created by MAC on 15/12/24. // Copyright © 2015年 MAC. All rights reserved. // #import "Demo.h" @implementation Demo -(void)method1{ NSLog(@"method1"); } -(void)method2{ NSLog(@"method2"); } -(void)executeSelector{ //定义 //SELW SEL S = @selector(method1); [self performSelector:S]; //2. NSSelectorFromString 方法名称可以没有 SEL s2 = NSSelectorFromString(@"method2"); [self performSelector:s2]; } @end
------------
// // Dog.h #import <Foundation/Foundation.h> #import "Animal.h" @interface Dog : Animal @end // // Dog.m #import "Dog.h" @implementation Dog -(void)run{ NSLog(@"dog is run..."); } @end
// // Cat.h #import <Foundation/Foundation.h> #import "Animal.h" @interface Cat : Animal @end // // Cat.m #import "Cat.h" @implementation Cat -(void)run{ NSLog(@"cat is run..."); } @end
#import <Foundation/Foundation.h> @interface Animal : NSObject @end #import "Animal.h" @implementation Animal @end
// Person.h #import <Foundation/Foundation.h> #import "Animal.h" @interface Person : NSObject -(void)care:(Animal*)pet; @end // // Person.m #import "Person.h" @implementation Person -(void)care:(Animal *)pet{ // [pet run]; SEL s = NSSelectorFromString(@"run"); [pet performSelector:s]; } @end