简体   繁体   English

两个对象可以互相代表吗?

[英]Can two objects be delegates of each other…?

Is it ok to have two objects as delgates of each other..? 是否可以将两个对象彼此用作代表。 My scenario is that I have a view which is shown in two modes.. first: Create mode and second: Edit mode 我的情况是,我有一个以两种模式显示的视图。.第一种:创建模式,第二种:编辑模式

In Create Mode all the fields are empty and I take data from the view which is filled in by the user and I update my data model. 在创建模式下,所有字段均为空,我从用户填写的视图中获取数据,然后更新数据模型。

And In View Mode I fill up the view from my data model. 在视图模式下,我从数据模型中填充视图。

This is being done using a spilt view controller(because of this I am forced to use delegation). 这是使用溢出的视图控制器完成的(因此,我不得不使用委派)。 I wish I could explain this better but this is the best I can do. 我希望我能对此做更好的解释,但这是我能做的最好的。 As of now I am using delegation to communicate from A to B and Notification from B to A. 到目前为止,我正在使用委托从A到B进行通信,并从B到A进行通知。

Would this work fine if I use delegation in both ways... or are there any complexities involved which I can't foresee? 如果我以两种方式使用委派,是否可以正常工作……还是有我无法预见的复杂性?

There are a few problems that could occur, but if you take the necessary precautions, it will be fine: 可能会发生一些问题,但是如果采取必要的预防措施,那就可以了:

  1. Ensure both delegates are weak referenced. 确保两个代表都被弱引用。 This means using @property (weak) on ARC or @property (assign) . 这意味着在ARC上使用@property (weak)@property (assign) This will prevent retain cycles from occurring. 这将防止发生保留周期。

  2. Ensure you don't get into a situation where a delegate method calls the delegate method of the other controller, which calls the same delegate method in the first controller and so on. 确保您不会遇到委托方法调用另一个控制器的委托方法的情况,后者在第一个控制器中调用相同的委托方法,依此类推。 You could easily get an infinite loop if you are not careful. 如果不小心,很容易会遇到无限循环。

A discussion or debate on whether or not this is the best design pattern in this situation is not really something that belongs on SO. 关于在这种情况下这是否是最佳设计模式的讨论或辩论并不是真正属于SO的事情。 But doing it this way is possible if you are careful, which is the answer to your question. 但是如果您小心的话,可以这样做,这就是您问题的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM