加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

objective-c – 非字母数字字符可以用作选择器吗?

发布时间:2020-12-16 06:56:41 所属栏目:百科 来源:网络整理
导读:以下代码编译并运行正常(请注意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
以下代码编译并运行正常(请注意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,i20);

    NSLog(@"%d + %d = %d",[i4 intValue],[i20 intValue],[res intValue]);
    //  >> 4 + 20 = 24

    [pool drain];
    return 0;
}

除了“哎呀”之外,还有理由对这样做持谨慎态度吗?

解决方法

ObjC运行时的API不太可能改变,但调用sel_registerName(“”)的有效性可能会改变.我已经在ObjC运行时中徘徊了很多,即使经过多次更新也没有遇到任何问题.话虽这么说,我不会在这个数百万美元的业务基础上继续工作.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读