Reputation: 2162
Consider this model:
@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
I want to update patientCount
every time a patient is added or removed. If this was a normal attribute I would simple override the setters/getters, but since they were generated by Core Data, I don't know how to do it.
What's to correct way? I don't want to fetch the patients just to count them and I don't want to use KVO for something this simple.
Upvotes: 2
Views: 1267
Reputation: 8988
Are you aware you can get patient count directly from hospital.patients.count ? Why bother keeping an attribute for this ?
But if you must, then implement methods similar to these in your managedObjectSubclass and update the relevant attribute within these methods.
- (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];
}
Upvotes: 2