背景:我有兴趣研究并尝试创建更好的随机数生成器作为个人实验。此外,我还学习并学习了Objective-C和iOS开发。因此,我认为一个很棒的练习项目是将我的随机数生成器创意移植到iOS应用程序中以获得乐趣。我有一个相当强大的Java背景,所以我做了几次之前我要提到的事情,但我的Objective-C技能非常令人高兴,所以我不确定如何解决这个问题。
意图:我正在使用UITableVIew提供我想出的生成器列表。再一次,这是为了试验我的想法,并练习我的iOS开发技巧,但我正在尝试做一些能使我未来的开发更清洁,更轻松的事情。我一直在尝试使用Obj-C协议来实现我正在尝试做的事情,因为根据我的研究和阅读它们实际上与Java中的接口相同。
所以,我想做的是能够定义一个协议(我已经知道该怎么做),要求“实现”该协议的任何人实现里面的方法(我已经知道该怎么做)但是能够声明协议定义的类型的对象,而不是特定的随机数类,这样就可以很容易地创建和添加新的生成器,因为我不必担心将任何内容链接到table,只需添加符合协议的新生成器类即可。我知道我想要什么,我知道这些话,我只是不确定如何表达它。
我做了什么:
在Java中,以下是可能的,有效的和通用的:
Bar.java
public interface Bar{
public void sayHello();
}
Foo.java
public class Foo implements Bar{
public void sayHello(){
System.out.println("Hello");
}
Main.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();
}
}
这将很好地打印到控制台。我已经看过许多人这样做的例子,我自己用Java做了好几次。
以下是我在Objective-C中尝试做的事情:
Bar.h 假设有必要#import
@protocol Bar : NSObject
-(NSInteger) generateRandomNumber;
@end
MyConformingViewController.m 假设已经声明了接口,并且处理了导入
@interface MyConformingViewController() <Bar>
@end
@implmentation MyConformingViewController
-(NSInteger) generateRandomNumber{
return 0;
}
@end
MyTableViewController.m 假设接口已经声明
@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,但它没有按照我希望的方式回答这个问题,而且我还阅读了我书中的所有文档和协议上的苹果。据我所知,我只是在思考太多而且非常简单。
流速:
声明协议
在视图控制器中实现协议
在Table View Controller中,能够创建实现该协议的对象实例
根据用户点击的内容加载选定的视图控制器
在表视图控制器中仅显示实现该协议的那些类
答案 0 :(得分:3)
我认为你几乎是对的,但是
Bar *bar = [[MyConformingViewController alloc] init];
应该是
id <Bar> bar = [[MyConformingViewController alloc] init];
因为id <Bar>
声明符合Bar
协议的Objective-C对象。