我现在应该知道这一点了,但我还是有点困惑。当我的应用程序从一个视图控制器导航到下一个视图控制器(通过导航控制器)时,我想在转到下一个 VC 之前“最终确定”当前 VC 的数据。我看到拦截“页面交换”的唯一方法是在 [旧视图 viewWillDisappear] -> [newView viewWillAppear] 转换。这看起来很奇怪,但我想它工作正常。
这真的是处理导航转换的正确方法吗?我的应用程序是一堆 VC,它们共同构建一个数据库文件。每个 VC 处理数据的不同方面。
I should know this by now, but I am still a bit confused. When my app navigates from one view controller to the next (via the navigation controller) I want to "finalize" the data for the current VC before going to the next VC. The only way I see to intercept the "page swap" is in the [old view viewWillDisappear] -> [newView viewWillAppear] transition. It seems weird, though I guess it works okay.
Is that really the right way to handle navigation transitions? My app is a bunch of VCs which collectively build a database file. Each VC deals with a different aspect of the data.
发布评论
评论(2)
我不知道您的确切设置,所以这可能对您没有用,但我在使用
-(void)textFieldDidEndEditing:(UITextField*)tf
中保存数据方面有很好的经验tf.tag 来索引字段。从那里我将数据提交到存储类,并且不用担心 UI 中发生的情况。I don't know your exact setup, so this may not be useful to you, but I have good experiences with saving data in
-(void)textFieldDidEndEditing:(UITextField*)tf
, usingtf.tag
to index the fields. From there I commit the data to a storage class, and have no worries about what happens in the UI.“最终确定”部分到底涉及什么?我假设您在视图控制器中存储各个字段的一些状态,然后您想在进入下一个视图之前将其写入数据库文件?
当谈到“编辑视图控制器”时,我发现一个很好的方法是让视图控制器直接写入一个简单的模型对象,该对象在将其推送到导航控制器之前通过属性注入。
就像这样:
然后,当文本字段结束编辑或其他操作时,每个视图控制器通过设置属性等写入该模型。让视图控制器直接写入对象意味着您不需要处理 viewWillDisappear 等。
但是,如果您仍然需要这样做,您可以向导航控制器添加委托并处理这两个方法:
请参阅 UINavigationControllerDelegate 文档了解更多信息。
这将使您将逻辑保留在一个地方,而不是分散在每个视图控制器中。
What exactly is involved in the "finalizing" part? I assume you are storing some state in the view controller for various fields and then you want to write that to the database file before going on to the next view?
When it comes to "edit view controllers" I find a nice way to do it is to have the view controller directly write to a simple model object which is injected through a property before pushing it to the nav controller.
So something like:
Then each view controller writes to this model by setting properties etc. when a text field ends editing or whatever. Having the view controller write straight to the object means you don't need to handle viewWillDisappear etc.
If you do still need to do this however you can add a delegate to the navigation controller and handle these two methods:
See the UINavigationControllerDelegate documentation for more information.
This will let you keep the logic in one place rather than spread out in each view controller.