背景:作为个人实验,我有兴趣研究并尝试创建更好的随机数生成器。此外,我还开始学习 Objective-C 和 iOS 开发。因此,我认为一个很好的实践项目是将我的随机数生成器想法移植到 iOS 应用程序中以获得乐趣。我在 Java 方面有很强的背景,所以我已经做过好几次我之前要提到的事情,但是我的 Objective-C 技能很幼稚,所以我不确定如何去做。
意图:我正在使用 UITableVIew 提供我想出的生成器列表。同样,这是为了试验我的想法,并练习我的 iOS 开发技能,但我正在尝试做一些能让我 future 的开发更清晰、更容易的事情。我一直在尝试使用 Obj-C 协议(protocol)来实现我想要做的事情,因为根据我的研究和阅读,它们实际上与 Java 中的接口(interface)相同。
所以,我想做的是能够定义一个协议(protocol)(我已经知道该怎么做),要求任何“实现”该协议(protocol)的人实现其中的方法(我已经知道该怎么做)但是能够声明协议(protocol)定义的类型的对象,而不是特定的随机数类,这样创建和添加新生成器到列表很容易,因为我不必担心将任何东西链接到表,只需添加符合协议(protocol)的新生成器类即可。我知道我想要什么,我知道这些词,我只是不确定如何表达它。
我做了什么:
在 Java 中,以下是可能的、有效的和常见的:
Bar.java
public interface Bar{
public void sayHello();
}
Foo.java
public class Foo implements Bar{
public void sayHello(){
System.out.println("Hello");
}
主.java
import com.somepackage.*;//so we can go ahead and pickup everything I've put in there
public class Main{
public static void main(String[] args){
Bar bar = new Foo();//usually figure out how I'm going to autoload the class instead of instantiating it manually so as not to break my architecture and pluggability.
bar.sayHello();
}
}
这将很好地向控制台打印 Hello。我见过很多人这样做的例子,我自己也用 Java 做过几次。
这是我在 Objective-C 中尝试做的事情:
Bar.h 假设必要#import
@protocol Bar : NSObject
-(NSInteger) generateRandomNumber;
@end
MyConformingViewController.m 假设已经声明了接口(interface),并且处理了导入
@interface MyConformingViewController() <Bar>
@end
@implmentation MyConformingViewController
-(NSInteger) generateRandomNumber{
return 0;
}
@end
MyTableViewController.m 假设接口(interface)已经声明
@interface MyTableViewController
@end
@implementation MyTableViewController
//assume normal methods for a view controller are in place
//only load views into the table view that conform to that protocol
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
Bar *bar = [[MyConformingViewController alloc] init];//build will fail
//insert proper logic to load the view tapped on based on whether or not it conforms to that protocol
}
@end
问题结束
所以我在这里想弄清楚的是如何模拟我在 Java 中所做的事情。其中大部分我自己都能弄清楚,但我很难用措辞表达我遇到的这个特定问题。如果您需要更多信息或有任何其他架构建议,请告诉我。我看过 this question on protocols,但它没有按照我希望的方式回答问题,而且我还阅读了我的书中和苹果关于协议(protocol)的所有文档。据我所知,我只是想得太辛苦了,这很简单。
流程:
声明协议(protocol)
在 View Controller 中实现协议(protocol)
在 TableView Controller 中,能够创建实现该协议(protocol)的对象实例
根据用户点击的内容加载选定的 View Controller
在 TableView Controller 中只显示那些实现该协议(protocol)的类
最佳答案
我想你几乎是对的,但是
Bar *bar = [[MyConformingViewController alloc] init];
应该是
id <Bar> bar = [[MyConformingViewController alloc] init];
因为id <Bar>
声明一个符合 Bar
的 Objective-C 对象协议(protocol)。
关于java - 使用 Java 接口(interface)等 Obj-C 协议(protocol)实现类的可插拔性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20766254/