非字母数字字符可以用作选择器吗?
|
以下代码可以编译并正常运行(请注意
sel_registerName(\"+\")
):
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
#import <objc/message.h>
@interface Integer : NSObject
{
NSInteger intValue;
}
@property (assign) NSInteger intValue;
@end
@implementation Integer
@synthesize intValue;
- (id) plus:(Integer*)anInteger
{
Integer* outInt = [Integer new];
[outInt setIntValue: intValue + [anInteger intValue]];
return outInt;
}
@end
int main (int argc, char const *argv[])
{
id pool = [[NSAutoreleasePool alloc] init];
SEL plusSel = sel_registerName(\"+\");
Method m = class_getInstanceMethod([Integer class], @selector(plus:));
class_addMethod([Integer class], plusSel, method_getImplementation(m), method_getTypeEncoding(m));
Integer* i4 = [Integer new];
Integer* i20 = [Integer new];
[i4 setIntValue: 4];
[i20 setIntValue: 20];
Integer* res = objc_msgSend(i4, plusSel, i20);
NSLog(@\"%d + %d = %d\", [i4 intValue], [i20 intValue], [res intValue]);
// >> 4 + 20 = 24
[pool drain];
return 0;
}
除了\“ yuck \\”之外,还有其他理由对此采取谨慎态度吗?
没有找到相关结果
已邀请:
2 个回复
淑灯
填盖
发送该选择器的消息,并且不尝试执行ѭ3like之类的操作(这将导致编译错误),则没有理由害怕。 已注册的Objective-C选择器实际上是运行时系统在内部存储的C字符串。运行时系统保留一个指向C字符串的指针表,即所谓的SEL集。当您调用
时,ObjC运行时系统将为您的字符串以及SEL集中存储的每个C字符串调用
。如果SEL集中的任何C字符串等于您要注册的C字符串,则该函数将返回该集中相应C字符串的地址。否则,系统将复制您的字符串(带有
),将结果指针存储在SEL集中并返回它。这个新的指针成为一个新的唯一选择器。