忽略目标C中的消息

时间:2009-02-27 18:53:28

标签: objective-c

我有一些obj-c代码,我打算在插件中发送不支持的消息。但是,我似乎无法忽略消息。我想“ - (id)forward:(SEL)选择器:(marg_list)arglist;”会解决它,但它没有。如何在没有收到警告和终止呼叫的情况下完全运行此应用程序?

#import <stdio.h>
#import <objc/Object.h>

//------- @interface section -------

@interface Fraction: Object
{
    int  numerator;
    int  denominator;
}

-(void)   print;
-(void)   setNumerator: (int) n;
-(void)   setDenominator: (int) d;
-(id)     forward: (SEL) selector: (marg_list) arglist;

@end

//------- @implementation section -------


@implementation Fraction;
-(void) print
{
    printf (" %i/%i ", numerator, denominator);
}

-(void) setNumerator: (int) n
{
    numerator = n;
}

-(void) setDenominator: (int) d
{
    denominator = d;
}

-(id) forward: (SEL) selector: (marg_list) arglist
{
    return nil;
}

@end

//------- program section -------


int main (int argc, char *argv[])
{
    Fraction  *myFraction;

    // Create an instance of a Fraction

    myFraction = [Fraction alloc];
    myFraction = [myFraction init];

    // Set fraction to 1/3

    [myFraction setNumerator: 1];
    [myFraction setDenominator: 3];

    // Display the fraction using the print method

    printf ("The value of myFraction is:");
    [myFraction print];
    printf ("\n");
    [myFraction someMsg: 99];
    [myFraction free];
    printf("end");  
    return 0;
}

1 个答案:

答案 0 :(得分:1)

最好在调用者中执行此操作,而不是将其插入插件中。而不是:

[myFraction someMsg: 99];

您应该检查myFraction是否响应someMsg选择器:

if ([myFraction respondsToSelector:@selector(someMsg:)]) {
    [myFraction someMsg: 99];
}

-respondsToSelector:方法在NSObject Protocol Reference中定义,请注意您的MyFraction对象需要从NSObject继承,而不是Object(或者是你自己的NSObject协议。当然,这无论如何都是最佳实践 - 通常不鼓励直接继承Object类。