OC - SEL类型的使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Gilgamesho/article/details/50590582

一.SEL类型的第一个作用, 配合对象/类来检查对象/类中有没有实现某一个方法

SEL sel = @selector(setAge:);
Class *p = [Class new];
  1. 判断p对象中有没有实现-号开头的setAge:方法
  2. 如果P对象实现了setAge:方法那么就会返回YES
  3. 如果P对象没有实现setAge:方法那么就会返回NO
BOOL flag = [p respondsToSelector:sel];
NSLog(@"flag = %i", flag);

A. respondsToSelector注意点:
1. 如果是通过一个对象来调用该方法那么会判断该对象有没有实现-号开头的方法
2. 如果是通过类来调用该方法, 那么会判断该类有没有实现+号开头的方法

SEL sel = @selector(test);
flag = [p respondsToSelector:sel];
NSLog(@"flag = %i", flag);
flag = [Class respondsToSelector:sel];
NSLog(@"flag = %i", flag);

二. SEL类型的第二个作用, 配合对象/类来调用某一个SEL方法

SEL sel = @selector(test);
Class *p = [Class new];
  1. 调用p对象中sel类型对应的方法
[p performSelector:sel];
SEL sel = @selector(signalWithNumber:);
  1. withObject: 需要传递的参数
    A.注意:
    如果通过performSelector调用有参数的方法, 那么参数必须是对象类型,
    也就是说方法的形参必须接受的是一个对象, 因为withObject只能传递一个对象
[p performSelector:sel withObject:@"XXXXX"];
SEL sel2 = @selector(setAge:);
[p performSelector:sel withObject:@"XXXXX"];
NSLog(@"age = %i", p.age);

B.注意:performSelector最多只能传递2个参数

SEL sel = @selector(sendMessageWithNumber:andContent:);
[p performSelector:sel withObject:@"XXXXX" withObject:@"XXXXX"];

三. 配合对象将SEL类型作为方法的形参

Class *c = [Class new];
SEL sel = @selector(test);
ClassTwo *p = [ClassTwo new];
[p makeObject:c andSel:sel];
附上apple文档:(一切以以下为准)
•   Defines an opaque type that represents a method selector. 

Declaration

typedef struct objc_selector *SEL;

Discussion
Method selectors are used to represent the name of a method at runtime. A method selector is a C string that has been registered (ormapped“) with the Objective-C runtime. Selectors generated by the compiler are automatically mapped by the runtime when the class is loaded. 
You can add new selectors at runtime and retrieve existing selectors using the function sel_registerName. 
When using selectors, you must use the value returned from sel_registerName or the Objective-C compiler directive @selector(). You cannot simply cast a C string to SEL. 

Import Statement

objc_method_description 
Defines an Objective-C method. 

Declaration

struct objc_method_description { SEL name; char *types; }; 


Fields
name The name of the method at runtime. 

types The types of the method arguments.

猜你喜欢

转载自blog.csdn.net/Gilgamesho/article/details/50590582