Why is it that sending any selector to a Nil object does nothing, but sending an “invalid” selector to any NSObject raises an exception?

前端 未结 3 608
囚心锁ツ
囚心锁ツ 2020-12-16 17:47

Does anyone know why NextStep/Apple decided to take the \"convenient method\" of doing nothing when passing a Nil object a message, but the \"Java method\" of raising an exc

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-16 18:37

    For everyone's amusement, due to the discussion CodaFi and I were having, here's a quickly-hacked-together way to eat normally unresponded-to messages and have them return nil:

    @interface EaterOfBadMessages : NSObject 
    @end
    
    @implementation EaterOfBadMessages
    
    - (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector 
    {
        NSMethodSignature * sig = [super methodSignatureForSelector:aSelector];
        if( !sig ){
            sig = [NSMethodSignature signatureWithObjCTypes:"@@:"];
        }
        return sig;
    }
    
    - (void)forwardInvocation:(NSInvocation *)anInvocation 
    {
        id nilPtr = nil;
        [anInvocation setReturnValue:&nilPtr];
    }
    
    @end
    
    int main(int argc, const char * argv[])
    {
    
        @autoreleasepool {
    
            EaterOfBadMessages * e = [[EaterOfBadMessages alloc] init];
            // Of course, pre-ARC you could write [e chewOnThis]
            NSLog(@"-[EaterOfBadMessages chewOnThis]: %@", [e performSelector:@selector(chewOnThis)]);
    
        }
        return 0;
    }
    

    Please don't use this in real life.

提交回复
热议问题