gpt4 book ai didi

iphone - 实例方法调用类方法调用实例方法

转载 作者:太空狗 更新时间:2023-10-30 03:50:24 26 4
gpt4 key购买 nike

一句话,怎么样?

我有一个创建一些自定义对象的 View Controller 。其中一个对象需要在 Controller 中调用一个方法。该对象看起来像是要调用 Controller 中的类方法,这可能没问题,只是 Controller 中的类需要调用 Controller 中的实例方法,而且它似乎不想这样做。这有意义吗?

如果不是,这是伪代码:


ViewController.m

#import "customObj.h"
-(void)viewDidLoad{
foobar=@"string";//declared in ViewController.h
}
-(void)createObj{
foobar=@"different string";
customObj *customObjInstance=[[customObj alloc] init];
}

---

customObj.m

#import "ViewController.h"
-(void)callBack{
[ViewController createObj];
}

好的,所以当 callBack 运行时,它出错了,说它正在寻找 +createObj(而不是 -createObj)。我可以将 createObj 更改为类方法,但是设置 foobar 时会出现问题,因为 foobar 是在 -viewDidLoad 中初始化的,我无法将其更改为 +viewDidLoad。我也许可以将 foobar 移出到类方法中,但是我该如何调用它呢?我指的是 [ViewController ...] 而不是 self 吗?我认为这行不通。

我的猜测是我遗漏了一些基本概念,而且它并不像我正在做的那样困难。我很感激任何能帮我解决问题的人。

非常感谢。

最佳答案

没有唯一的正确答案;这取决于您的自定义对象如何与 Controller 交互。大多数 UIKit View 使用“目标-操作”模式与 Controller 通信,而许多模型对象使用委托(delegate)模式。您使用哪一个取决于您的 Controller 和自定义对象的具体情况。

但是,从机制上讲,您可能需要做的是在通过自定义初始化程序创建 customObj 时传递一个指向您的 ViewController 的指针,如下所示:

customObj *customObjInstance = [[customObj alloc] initWithController: self];

如果您这样做,请确保您的 customObj 与您的 Controller 紧密耦合是有意义的。

关于iphone - 实例方法调用类方法调用实例方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1096031/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com