gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:09:14 25 4
gpt4 key购买 nike

考虑这个模型:

@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/getter,但由于它们是由 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];
}

关于ios - 在关系中添加/删除对象时更新属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20315952/

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