<分区>
我知道如何在 java 中做到这一点,但我在 objetice-c 中遇到问题
在 java 中我会有这样的接口(interface):
public interface Car {
public void startCar();
}
以及将实现此接口(interface)的类:
public class SomeCarImpl implements Car {
public void startCar() {
System.out.println("starting the car...");
}
}
现在我可以在我的主课上做到这一点
public void MainClass {
public static void main(String [] args) {
Car myCar = new SomeCarImpl();
car.startCar();
}
}
现在我在 objective-c 中遇到了麻烦。前两件事很容易用协议(protocol)来实现,但是当我想这样调用它时,什么也没有发生
//header
id <Car> *myCar;
//instance
myCar = [[SomeCarImpl alloc] init];
//calling and nothing happens
[myCar startCar];
我希望你能理解我的问题...并帮助我 :-)
//这里是代码
@interface SomeCarImpl:NSObject<Car>
@end
@implementation SomeCarImpl
-(void)startCar{
NSLog(@"run");
}
@end
@protocol Car <NSObject>
-(void)startCar;
@end
@interface DetailViewController:UIViewController<UISplitViewControllerDelegate> {
IBOutlet UIButton *runButton;
id<Car> myCar;
}
@property(strong, nonatomic)IBOutlet UIButton *runButton;
@property(strong, nonatomic)id<Car> myCar;
@end
最后(detailViewController.myCar = [[SomeCarImpl]alloc]init] 预先在 tableView 中调用)
-(IBAction)runButton:(id)sender {
[myCar startCar];
}
最佳答案
你的 Java 代码会模糊地翻译成这样的东西:
//public interface Car {
// public void startCar();
//}
@protocol Car
- (void)startCar;
@end
//public class SomeCarImpl implements Car {
// public void startCar() {
// System.out.println("starting the car...");
// }
//}
@interface SomeCarImpl : NSObject<Car>
@end
@implementation SomeCarImpl
- (void)startCar {
NSLog(@"starting the car...");
}
@end
// Car myCar = new SomeCarImpl();
// car.startCar();
id<Car> myCar = [[SomeCarImpl alloc] init];
[myCar startCar];
在您的 ObjC 代码中,您需要从此行中删除星号:
id <Car> *myCar;
因为 id
类型已经是一个指针(虽然我不认为这不是你问题的根源)。
关于objective-c - 一些协议(protocol)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6925430/