iphone - 如何抽象 Objective C 中的类名或类型以用作变量?

标签 iphone ios objective-c abstract-class

我已经意识到我的几个 ListView Controller 的行为方式相同,现在我想将它们抽象为一个通用的,称为 ListVC。计划是在需要时创建一个 ListVC 实例,并将该实例所需的所有特定内容传递给它。

例如,如果我需要一个客户列表,我会这样做:

ListVC *customersVC = [[ListVC alloc] init];
customersVC.tableArray = self.customersList

在 ListVC 中,有时我需要知道某个对象的类类型。在我的示例中,数组 self.customersList 中的对象来自类 CustomerClass。我知道我可以 convert strings to class names 但当我在 ListVC 中有一个方法需要返回对象的类型时,这无济于事。例如,在 ListVC 中,这个旧的非抽象方法:

- (CustomerClass *)customerAfterFilter

应该是这样的:

- (self.objectClass *)objectAfterFilter

我会像这样实例化后设置 objectClass。

ListVC *customersVC = [[ListVC alloc] init];
customersVC.tableArray = self.customersList    
customersVC.objectClass = [CustomerClass class];

我该如何做这样的事情?或者,如果我的方法是错误的,请提出正确的方法。我是编程初学者。

最佳答案

你不能那样改变返回类型。您可以做的是返回一个 id,它是指向任何类对象的指针。

- (id)objectAfterFilter

编辑:

Customer *c = [customersVC objectsAfterFilter];
[c duCustomerStuff];

或者:

[((Customer *)[customersVC objectsAfterFilter]) doCustomerStuff];

关于iphone - 如何抽象 Objective C 中的类名或类型以用作变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15646603/

相关文章:

ios - ALAssetsLibrary 在保存到相册时询问用户许可吗?为什么?

iphone - 在图像上创建一个图层并通过触摸调整其坐标

ios - 如何在 Swift 3 中将 edgesForExtendedLayout 设置为 none

ios - iCarousel 上的缩放变换显示屏幕外区域

iOS 滚动 tableView 可重用单元格重新加载

iphone - poptorootviewcontroller 不按顺序调用 Root View Controller 的 dealloc 方法和 viewdidappear 方法

iphone - AFNetworking setImageWithURL - 获取返回图像的高度?

ios - 使用 Xcode 9 和 Swift 4 本地化应用程序的最佳方式?

iphone - iPhone 中 url 的正则表达式

ios - 删除观察者: forKeyPath is not working