开发者

Setting an iterated value for an attribute by counting related items in Core Data

开发者 https://www.devze.com 2023-03-11 13:35 出处:网络
I\'m trying to set an attribute value to an automatically iterated number based on a to one relationship. I have an entity called \"Encounter\" that has a to many relationship to \"Round\" and I need

I'm trying to set an attribute value to an automatically iterated number based on a to one relationship. I have an entity called "Encounter" that has a to many relationship to "Round" and I need the attribute to simply iterate to the next value and reflect the number of rounds currently related to the Encounter entity. I have the appropriate data model, tabel views, and array controllers bound and set up in interface builder and they all work fine. But when I try to refer开发者_开发知识库ence the encounter property from my Round subclass fo NSManagedObject, I get just get null.

ex:

- (void) awakeFromInsert{
    [super awakeFromInsert];    
    Encounter *enc = [self encounter];
    NSUInteger roundCount = [[enc rounds]count];
    [self setValue:[NSNumber numberWithUnsignedInteger:roundCount] forKey:@"roundNumber"];
    }

I also tried creating a method that executes a fetch request ont he Managed Object Context but I haven't figured out how to write a predicate that only pulls the related records to count. I'm sure this is something simple that I'm missing and I would appreciate any assistance.


I figured out a solution that seems to work well. Basically, I subclassed the NSArrayController and overrode the addObject method to look like the following with "Round" being the name of the NSManagedObject subclass:

-(id)newObject{
    Round *round = (Round *)[super newObject];
    round.roundNumber = [NSNumber numberWithUnsignedInteger:[[self arrangedObjects]count]+1];
    return round;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号