objective-c - 一些协议(protocol)问题

标签 objective-c ios interface protocols

<分区>


想改进这个问题吗? 更新问题,使其只关注一个问题 editing this post .

关闭 9 年前

我知道如何在 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/

上一篇:iphone - UIView 动画 block UIView 交互

下一篇:iphone - EXEC_BAD_ACCESS 当我尝试释放分配有地址的 NSString 时

相关文章:

ios - 使用 Screen Edge Pan Gesture Recognizer 在 WebView 中后退和前进

c# - 接口(interface)应该尽可能通用吗?

java - 为什么接口(interface)方法不能是 "static"& "final"?

ios - 如何在Ios中获取视频的Instagram Media_ID?

go - 有没有一种方法可以通用地表示一组相似的函数?

iphone - 单例类内存泄漏

objective-c - 如何交互(点击)隐藏的物体?

ios - 如何将静态 UIButton 覆盖 UITableView

ios - 您可以在不删除对象然后再次添加它们的情况下更新核心数据吗? - iOS

ios - 在运行模拟器时设置标准用户默认值不会保存数据