代码之家  ›  专栏  ›  技术社区  ›  Thomas Joulin

重写目标C类中的方法

  •  3
  • Thomas Joulin  · 技术社区  · 14 年前

    为什么我不能这样做,我如何才能在目标C中执行相同的行为?

    @interface Test
    {
    
    }
    
    - (void)test:(Foo *)fooBar;
    - (void)test:(Bar *)fooBar;
    
    @end
    

    提前谢谢!

    3 回复  |  直到 14 年前
        1
  •  5
  •   Marcelo Cantos    14 年前

    这称为重载,而不是重写。objective-c方法不支持类型重载,只支持方法名和参数名重载(不管怎样,“重载”并不是一个很好的术语)。

        2
  •  5
  •   Nick Moore Wain    14 年前

    惯例是根据接受的参数对方法名进行更改:

    - (void)testWithFoo:(Foo *)foo;
    - (void)testWithBar:(Bar *)bar;
    
        3
  •  4
  •   andyvn22    14 年前

    不,你不能这样做。实际上,正如你所说,obj-c的“高度动态”特性使它成为一个相当糟糕的主意;想象一下:

    id objectOfSomeType = [foo methodReturningId]; //It's not clear what class this is
    [Test test:objectOfSomeType]; //Which method is called? I dunno! It's confusing.
    

    如果你真的,真的想要这种行为,我 假设 你可以这样实现它:

    - (void)test:(id)fooBar
    {
        if ([fooBar isKindOfClass:[Foo class]])
        {
            //Stuff
        }
        else if ([fooBar isKindOfClass:[Bar class]])
        {
            //You get the point
        }
    }
    

    不过,在我能想到的所有情况下,最适合使用不变量的方法:

    - (void)testWithFoo:(Foo *)foo;
    - (void)testWithBar:(Bar *)bar;