菜鸟教程小白 发表于 2022-12-12 16:49:26

ios - 我在哪里使用 Core Data 将业务逻辑放在 IOS 应用程序中?


                                            <p><p>我刚刚开始探索 ios 和 xcode,并开始构建使用 Core Data 的应用程序。</p>

<p>在我的模型中,我有 2 个相关实体:</p>

<ul>
<li>具有examDate 和studyStartDate 的考试实体</li>
<li>用于计划/记录考试准备的 CalendarItem。</li>
</ul>

<p> <a href="/image/5ceYa.png" rel="noreferrer noopener nofollow"><img src="/image/5ceYa.png" alt="Section of my data model"/></a> </p>

<p>业务逻辑的一部分是:对于 studyStartDate 和examDate 之间的所有日期,我想要一个CalendarItem。</p>

<p>因此,为此,我需要在每次日期范围的开始和结束(在 studyStartDate 和examDate 中)更改时创建/删除 CalendarItems 的代码。</p>

<p>在其他帖子(例如 <a href="https://stackoverflow.com/questions/4415904/business-logic-in-mvc?lq=1" rel="noreferrer noopener nofollow">here</a>)中,我读到这种类型的业务逻辑应该放在模型中(而不是在 Controller 中)。所以现在我需要在我的模型中找到一个可以编写代码的地方。</p>

<p>我的问题是:我在哪里创建此代码?
在考试项目的 NSManagedObject 的子类中?如何访问examItem 中的ManagedObjectContext(如果在我的模型中插入/删除其他记录,我认为我需要它)?
还是我需要继承 NSManagedObjectContext 并在那里构建我的逻辑?</p>

<p>我真的迷路了。</p>

<p><strong>更新:</strong><br/>
感谢下面的答案,我或多或少地跟进了数据库管理器模型。尝试保持 ManagedObjects 简单并专注于单个实体是正确的方向。</p>

<p>我创建了一个类 CalendarManager,我在 appdelegate 中实例化了一次。它接收 ManagedObjectContext。它订阅通知中心中的插入/删除通知,并为每个新考试设置键值观察器。 </p>

<p>顺便说一句:KVO 只需要关注考试中的日期项目。不幸的是,无法使用 NSManagedObjectContextObjectsDidChangeNotification。这会陷入无休止的循环:添加/删除相关的 CalendarItem 也会改变 Exam,这会触发另一个循环。</p>

<p><strong>CalendarManager.h</strong></p>

<pre><code>#import &lt;CoreData/CoreData.h&gt;

@interface CalendarManager : NSObject

-(id)initWith:(NSManagedObjectContext *)moc;

@end
</code></pre>

<p><strong>CalendarManager.m</strong></p>

<pre><code>#import &#34;CalendarManager.h&#34;
#import &#34;Exam.h&#34; // NSManagedObject subclass
#import &#34;CalendarItem.h&#34; // NSManagedObject subclass

@interface CalendarManager ()

-(void)updateCalendarItemsFor:(Exam*)exam;
-(void)setObserverFor:(Exam*)exam;
-(void)removeObserverFor:(Exam*)exam;

@property NSArray *keyPaths;
@property NSManagedObjectContext *moc;

@end
</code></pre>

<p>这样对我有用。</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>我总是创建一个具有 NSManagedObjectContext 并插入/删除的 DatabaseManager。我的妈妈们只是愚蠢的类(class),没有任何逻辑:P</p>

<p>但我想说这是一个见仁见智的问题</p></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 我在哪里使用 Core Data 将业务逻辑放在 IOS 应用程序中?,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/33297756/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/33297756/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 我在哪里使用 Core Data 将业务逻辑放在 IOS 应用程序中?