Objective-C –将 ViewController 设置为另一个类的委托的正确过程

发布于 2024-11-27 06:07:47 字数 542 浏览 0 评论 0原文

假设我有 1 个视图控制器和一个模型类; ViewControllerModel

Model 中,我有一个如下所示的方法:

[object setDelegate:self]

相反,我希望 ViewController 充当委托。我将如何以及在哪里执行此操作?

我应该在模型的 - init 方法中allocinit我的ViewController吗:

ViewController *newVc = [[ViewController alloc] init];
[self setVc:newVc]; // retains newVc
[newVc release];

然后做:

[object setDelegate:[self vc]];

请对此进行一些说明。

Say I have 1 View Controller and one Model class; ViewController and Model

In Model I have a method that looks like this:

[object setDelegate:self]

Instead I want ViewController to act as the delegate. How and where would I do this?

Should I alloc and init my ViewController in my - init method of the Model like:

ViewController *newVc = [[ViewController alloc] init];
[self setVc:newVc]; // retains newVc
[newVc release];

And then do:

[object setDelegate:[self vc]];

Please throw some light on this.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

双马尾 2024-12-04 06:07:47

你可以这样做,但是如果object是你的模型,你可能会遇到循环引用的问题,你的模型保留了viewController,而你的viewController保留了你的模型,两者都不会到达调用dealloc方法来释放另一个。我会考虑使用通知,您的视图控制器可以直接连接到您的模型,但您的模型可以将更改广播给任何关心的人,然后您的视图控制器可以观察来自您模型的通知。我通常认为我的模型代码应该能够在任何接口上运行,甚至作为命令行程序。

You can do that but if object is you model you may have an issue with circular references, you have you model retaining the the viewController and your viewController retaining your model, neither is going to get there dealloc method called to release the other. I would look at using notifications your view controller can have a direct connection to you model but your model can broadcast changes to anybody who cares, you view controller can then observer an notification from you model. I usually like to think that my model code should be able to function with any interface, even as a command line program.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文