是否可以从实例化类中调用方法?
我有一个派生自 UITableViewController 的类,它处理与特定类型的表相关的所有内容。我们将其称为T 类
在主应用程序类A
中,我有方法来填充屏幕的其他区域,例如地图。
当我在 T 类
中填充表格时,我想调用 A 类
方法来绘制 x,y
点地图。
这可能吗?执行此操作的正确方法应该是什么?
当我想到这种方法时,我期望在 Class T
内调用 [super ...]
会调用 Class A
方法,如下所示这是实例的所有者类,但它当然调用父类,在我的例子中是 UITableViewController 。
谢谢你,
佩德罗
I have a class that is derived of UITableViewController and handles everything related with a specific type of tables. Let's call it Class T
In may main application class, Class A
, I have methods to populate other areas of the screen as, for instance, a map.
While I'm populating my table within Class T
, I would like to call the Class A
method that plots the x,y
points on the map.
Is this possible? What should be the correct way to do this?
When I though about this approach, I was expecting that invoking [super ...]
inside Class T
would call the Class A
methods, as this is the owner class of the instance, but ofcourse it call the parent class, in my case the UITableViewController
.
Thank you,
Pedro
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果
A
是您的主应用程序类,您应该能够使用[UIApplication sharedApplication]
访问应用程序实例,并将其强制转换为类A
输入,并调用您需要调用的API。If
A
is your main application class, you should be able to access the application instance with[UIApplication sharedApplication]
, cast it to the classA
type, and call the APIs you need to call.为什么不定义一个ClassAProtocol,然后在T类中添加一个属性“classADelegate”?
ClassAProtocol 将定义一个方法,如下所示:
因此,在 Class T 接口中,您将添加:
将执行以下操作:
然后当您实例化时,比方说从instanceA(A类的实例)、instanceT(T类的实例),您将执行以下操作:最后在 Class T 中,您 可以这样调用绘图方法:
在这种情况下,委托模式的优点是 Class T 只需要知道 ClassA 的一小部分,即协议,并且 ClassA 能够通过其实现与 T 进行通信协议的。
Why not define a ClassAProtocol and then add a property "classADelegate" in Class T?
ClassAProtocol will define a method like:
So in the Class T interface you will add:
and then when you instantiate, let's say from instanceA (instance of Class A), instanceT (instance of Class T) you will do:
Finally inside Class T you can call the plotting method in this way:
The advantage of the delegate pattern in this case is that Class T just need to know only one small piece of ClassA, which is the protocol, and ClassA is able to communicate with T thanks to its implementation of the protocol.