Objective-C –将 ViewController 设置为另一个类的委托的正确过程
假设我有 1 个视图控制器和一个模型类; ViewController
和 Model
在 Model
中,我有一个如下所示的方法:
[object setDelegate:self]
相反,我希望 ViewController 充当委托。我将如何以及在哪里执行此操作?
我应该在模型的 - init
方法中alloc
和init
我的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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你可以这样做,但是如果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.