在关系中添加/删除对象时更新属性

考虑这个模型:

@class Patient; @interface Hospital : NSManagedObject @property (nonatomic, retain) NSString * name; @property (nonatomic, retain) NSNumber * patientCount; @property (nonatomic, retain) NSSet *patients; @end @interface Hospital (CoreDataGeneratedAccessors) - (void)addPatientsObject:(Patient *)value; - (void)removePatientsObject:(Patient *)value; - (void)addPatients:(NSSet *)values; - (void)removePatients:(NSSet *)values; @end 

我想在每次添加或删除患者时更新patientCount 。 如果这是一个普通的属性,我会简单地覆盖setter / getters,但由于它们是由Core Data生成的,所以我不知道该怎么做。

什么是纠正方式? 我不想仅仅为了计算它们而取得患者,而且我不想将KVO用于这么简单的事情。

您是否知道您可以直接从hospital.patients.count获得患者数量? 为什么要为此保留一个属性呢?

但是如果必须,那么在managedObjectSubclass中实现与这些类似的方法,并更新这些方法中的相关属性。

  - (void)addTasksObject:(TreeNode *)value { NSSet *changedObjects = [[NSSet alloc] initWithObjects:&value count:1]; [self willChangeValueForKey:@"tasks" withSetMutation:NSKeyValueUnionSetMutation usingObjects:changedObjects]; [[self primitiveValueForKey:@"tasks"] addObject:value]; [self didChangeValueForKey:@"tasks" withSetMutation:NSKeyValueUnionSetMutation usingObjects:changedObjects]; // Add code to update self.patientsCount here self.patientsCount = [NSNumber numberWithInt:[self.patientsCount intValue] + 1]; } - (void)removeTasksObject:(TreeNode *)value { NSSet *changedObjects = [[NSSet alloc] initWithObjects:&value count:1]; [self willChangeValueForKey:@"tasks" withSetMutation:NSKeyValueMinusSetMutation usingObjects:changedObjects]; [[self primitiveValueForKey:@"tasks"] removeObject:value]; [self didChangeValueForKey:@"tasks" withSetMutation:NSKeyValueMinusSetMutation usingObjects:changedObjects]; // Add code to update self.patientsCount here (better check not negative) self.patientsCount = [NSNumber numberWithInt:[self.patientsCount intValue] - 1]; } - (void)addTasks:(NSSet *)value { [self willChangeValueForKey:@"tasks" withSetMutation:NSKeyValueUnionSetMutation usingObjects:value]; [[self primitiveValueForKey:@"tasks"] unionSet:value]; [self didChangeValueForKey:@"tasks" withSetMutation:NSKeyValueUnionSetMutation usingObjects:value]; self.patientsCount = [NSNumber numberWithInt:self.patients.count]; } - (void)removeTasks:(NSSet *)value { [self willChangeValueForKey:@"tasks" withSetMutation:NSKeyValueMinusSetMutation usingObjects:value]; [[self primitiveValueForKey:@"tasks"] minusSet:value]; [self didChangeValueForKey:@"tasks" withSetMutation:NSKeyValueMinusSetMutation usingObjects:value]; self.patientsCount = [NSNumber numberWithInt:self.patients.count]; }