我正在开发一个基于 Cocoa 的应用程序,该应用程序将在用户交易过程中多次调用 Postgres 数据库(使用 PGSQLKit)。该应用程序是各种信息亭。
我想知道的是在整个应用程序中进行数据库调用的正确方法。本着 MVC 的精神,我知道我应该为从数据库返回的数据创建对象(我计划这样做),然后使用这些对象。我需要说明的是我应该在哪里进行数据库调用。
基本上我有以下这些问题:
-为了与数据库交互,我应该创建一个单独的数据库 Controller 类来进行数据库调用吗?我觉得直接从 View Controller 调用数据库是不合适的。
-假设我创建了一个数据库 Controller ,我的 View Controller 是否应该触发数据库 Controller 类并以这种方式进行数据库调用?
- 当应用程序加载时,我是否应该通过数据库 Controller 连接到数据集并在用户事务完成时关闭它?我将在整个交易过程中打几个电话,所以我认为我不应该每次都关闭连接。
最佳答案
-In order to interact with the database, should I create a separate database controller class that would make database calls? I feel making database calls directly from a view controller would not be appropriate.
正确。在某些情况下,您甚至可能在数据库 Controller 之上有另一层模型对象。大多数应用程序不应该关心数据存储在 Postgres 数据库中而不是其他方式。
-Assuming I create a database controller, should my view controllers trigger the database controller class and make DB calls that way?
通常是的。您的 View Controller 将观察模型并在需要数据时告诉模型。该模型将让观察者(包括 View Controller ,尽管模型不关心他们是谁)知道相关数据何时可用或更改。
-When the application loads, should I make a connection to the datase through the database controller and close it when the user's transaction is complete? I'll be making several calls throughout the transaction so I don't think i should close the connection each time.
这是数据库 Controller 的内部细节。通常这种对象会保持长期连接。通常,该连接是在第一次要求模型从数据库中获取它需要的数据时建立的,而不是“在应用程序启动时”。
关于objective-c - 为了符合 MVC,我应该如何在 Cocoa 应用程序中进行数据库调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12428608/