转换和传递协议作为方法参数

时间:2014-05-22 23:33:32

标签: ios objective-c

制作一个生物可以与他人一起复制的游戏。我已经定义了一个协议,以便某些生物可以繁殖。

但是,我似乎无法弄清楚如何正确施放和传递生物

// Creature may breed with any other creature allowed to breed
@protocol Mateable
-(void)mateWith:(id<Mateable> *)entity;
@end

当玩家触碰一个生物时,我有逻辑施放该生物并传递它:

// If user taps on a create that can breed, we make it happen...
if( [touching conformsToProtocol:@protocol(Mateable)] ){
    id<Mateable> mate = (id<Mateable>) touching;
    [player mateWith:mate];
}

但是,我收到了错误:

Cannot initialize the parameter of type '__autorelease <id>Mateable' with an lvalue of type '__strong id<Mateable>'

我如何正确施放并传递该生物作为参数?

1 个答案:

答案 0 :(得分:5)

*之后您不需要id因为id已经是指针类型

所以

// Creature may breed with any other creature allowed to breed
@protocol Mateable
-(void)mateWith:(id<Mateable>)entity;
@end 

您应该能够自己弄明白,因为mateid<Mateable>并且您将其传递给id<Mateable> *