다음 코드는 컴파일과 잘 실행 (유의 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;
}
,이 일에 대해 신중해야하는 이유가?
재미는 모든 종류의 재미에 사용할 수 있습니다. 이상적인 것은 아닙니다. –