简体   繁体   English

如何在iPhone应用程序中管理模型和视图?

[英]How do I manage models & views in an iPhone app?

I have a bunch of model objects that inherit from NSObject (Result). 我有一堆从NSObject(结果)继承的模型对象。 And I have a bunch of view objects that inherit from UIView (ResultView). 我有一堆从UIView(ResultView)继承的视图对象。 They exist in a 1:1 relationship (one model for one view). 它们以1:1关系存在(一个模型用于一个视图)。 In my controller I have an two arrays: one for Result objects and one for ResultView objects. 在控制器中,我有两个数组:一个用于Result对象,另一个用于ResultView对象。 The controller displays many of these result views and they can be added/deleted/reordered. 控制器显示许多这些结果视图,可以对其进行添加/删除/重新排序。 Trying to keep 2 arrays in sync (results & resultViews) isn't working out. 试图保持2个数组同步(结果和resultViews)无法解决。 How should I approach this problem? 我应该如何解决这个问题?

I'm considering initializing a view object with a model object (eg: an initWithResult: in my ResultView class and then retain a pointer to the Result object in the ResultView). 我正在考虑使用模型对象初始化视图对象(例如:在我的ResultView类中使用initWithResult :,然后在ResultView中保留指向Result对象的指针)。 Then I could do something like ResultView.result to access model data. 然后,我可以执行类似ResultView.result的操作来访问模型数据。 Is there a better solution? 有更好的解决方案吗? This would break MVC, wouldn't it? 这会破坏MVC,不是吗?

Unless you're trying to persist these model objects in a DB or something similar, I would put a view property on the model objects. 除非您试图将这些模型对象保留在数据库中或类似的东西中,否则我将把view属性放在模型对象上。 If you don't have to create the view for any reason, then just nil it out to save on memory. 如果您不必出于任何原因创建视图,则只需将其删除即可节省内存。

Does it break MVC? 它会破坏MVC吗? I guess. 我猜。 But if your model objects will always have a view associated with them, it starts to go into the blurry line area. 但是,如果模型对象始终具有与之关联的视图,则它将开始进入模糊线区域。 No programming god will send you to hell for breaking the standard a little bit. 没有编程神会因为一点点违反标准而将您送入地狱。

Do what's clean, optimal, and easiest for another programmer to understand when looking at your code. 在查看您的代码时,请执行干净,最佳和最容易让其他程序员理解的操作。

Ok, if I understand your question correctly, the model objects are persistent while the views are dynamically created/deleted. 好的,如果我正确理解了您的问题,则在动态创建/删除视图时,模型对象将是持久的。 You are relying implicitly on the index of the two arrays to achieve the mapping of two parts. 您隐式依赖于两个数组的索引来实现两部分的映射。 One simple way is to add a "model object id" in your view class. 一种简单的方法是在视图类中添加“模型对象ID”。 Then you can easily reference to the correct model object in the view. 然后,您可以轻松地在视图中引用正确的模型对象。

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

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