【问题标题】:Should I include the managed object context as a parameter to a method?我应该将托管对象上下文作为参数包含在方法中吗?
【发布时间】:2011-06-04 20:37:24
【问题描述】:

问题

当我使用 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
}

【问题讨论】:

    标签: objective-c cocoa methods coding-style


    【解决方案1】:

    以我(不是那么谦虚)的观点,我会说这主要是风格问题。你可以这样做,也可以@synthesize moc 并致电[self moc]self.moc

    我?我会亲自去访问器路线,主要是因为不应该告诉类成员在哪里可以找到被 iVar 取消引用的对象。如果您要访问同一类中的 iVar,我会直接使用 iVar 或访问器。

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

    【讨论】:

    • 与所有好的答案一样,事后看来,这似乎很明显。当然,这是这样做的方法。不敢相信我没有想到这一点。非常感谢您的帮助!
    猜你喜欢
    • 2019-07-20
    • 2012-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    • 2011-08-05
    相关资源
    最近更新 更多