开发者

How can I set a default value in NSManagedObject derived class based on existing NSManagedObject values?

开发者 https://www.devze.com 2023-02-15 09:17 出处:网络
I have an NSManagedObject derived class OrderMO that has a property OrderDate of type NSDate. I would like to have the default value for OrderDate be the first Monday of the month for the first month

I have an NSManagedObject derived class OrderMO that has a property OrderDate of type NSDate. I would like to have the default value for OrderDate be the first Monday of the month for the first month that does not already have an order associated with it.

To do this I am overriding the awakeFromInsert function of NSManagedObject and setting the value of OrderDate like this:

- (void) awakeFromInsert
{
    [super awakeFromInsert];
    [self setValue:[self getNextOrderDate] forKey:@"OrderDate"];
}

The custom function getNextOrderDate calculates the appropriate date and returns it. The problem is that getNextOrderDate calls executeFetchRequest which is apparently a no-no during the awakeFromInsert call. I've tried doing what is described in this article, but it did not solve my problem. In that article the problem is solved by calling self performSelector to delay the call to execute开发者_Python百科FetchRequest until after the NSManagedObject is initialized. In my case I just get 2 garbage rows.

I considered sub-classing my Orders ArrayController to override the add function, but don't really know what to do there either.

Can someone please tell me the proper way to initialize an NSManagedObject property based on existing NSManagedObjects of the same entity type, in the same array with a value that depends on the existing objects' values?


Well, one method would be to do a fetch for specific value. That returns just a dictionary and I'm pretty sure it won't trigger all the notifications associated with fetching faults or objects. You should be able to extract just the one date you want without setting off all the bells and whistles. However, I've never tested that in this particular circumstance.

Another approach would be to create the managedObject directly i.e. just like a non-managedObject, populate the attribute as you want and only then insert the managedObject into the context. Not very elegant but it will work and it won't set off a bunch of notifications.

Some Core Data hands write their own insertion class methods for their NSManagedObject subclass. You might want to employ that here. E.g.

+(OrderMO *) insertOrderMOIntoManagedObjectContext:(NSManagedObjectContext *) aContext{
    OrderMO *newOrder=[[OrderMO alloc] init];
    // pefrom fetch on aContext to find the next order date
    newOrder.orderDate=//... fetched order date
    [aContext insertObject:newOrder];
}
0

精彩评论

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