gpt4 book ai didi

objective-c - 我应该将托管对象上下文作为方法的参数包含在内吗?

转载 作者:行者123 更新时间:2023-12-03 16:39:05 25 4
gpt4 key购买 nike

问题

当我使用 Core Data 时,我将托管对象上下文作为方法的参数包含在内。

虽然这使代码更容易测试,但它很困惑。

问题

  • 这是好还是坏做法?
  • 有没有一种更简洁、更简单的方法来保持方法的可测试性?

背景

下面的示例是一个具有自己上下文的后台操作。

如果有经验丰富的编码人员提供任何建议,我们将不胜感激!

代码

@interface JGTrainingGroupCleanupOperation : JGCoreDataOperation {
NSManagedObjectContext *imoc;
}

...

@implementation JGTrainingGroupCleanupOperation

-(void)main {
[self startOperation]; // Setting up the local context etc
[self cleanupTrainingGroupsInMOC:imoc];
[self finishOperation];
}

-(void)cleanupTrainingGroupsInMOC:(NSManagedObjectContext *)moc {
NSSet *trainedGroups = [self fetchAllTrainedGroupsInMOC:moc];

[self deleteDescendantsOfGroups:trainedGroups fromMOC:moc];
[self removeStubAncestorsOfGroups:trainedGroups fromMOC:moc];
}

-(NSSet *)fetchAllTrainedGroupsInMOC:(NSManagedObjectContext *)moc_ {
return [moc_ fetchObjectsForEntityName:kTrainingGroup withPredicate:[NSPredicate predicateWithFormat:@"projectEditedAtTopLevel == nil"]];
}

-(void)deleteDescendantsOfGroups:(NSSet *)trainedGroups fromMOC:(NSManagedObjectContext *)moc_ {
// More code here
}

-(void)deleteDescendantsOfGroup:(JGTrainingGroup *)trainedGroup fromMOC:(NSManagedObjectContext *)moc_ {
// More code here
}

最佳答案

以我(不那么谦虚)的观点,我认为这主要是风格问题。您可以这样做,也可以@synthesize moc 并调用[self moc]self.moc

我?我个人会选择访问器路线,主要是因为无论如何都不应该告诉类成员在哪里找到 iVar 取消引用的对象。如果您要访问同一类中的 iVar,我会直接使用 iVar 或访问器。

相信性能差异可以忽略不计,所以我不会在这方面太费心(即使你没有问)。

关于objective-c - 我应该将托管对象上下文作为方法的参数包含在内吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4618713/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com