Cocoa Core Data: Setting default entity property values?

好久不见. 提交于 2019-12-06 11:02:41

SOLVED IT!

Ok, the problem of double entry occurs when a fetch request is performed from within the awakeFromInsert method. Quoting from the docs:

You are typically discouraged from performing fetches within an implementation of awakeFromInsert. Although it is allowed, execution of the fetch request can trigger the sending of internal Core Data notifications which may have unwanted side-effects. For example, on Mac OS X, an instance of NSArrayController may end up inserting a new object into its content array twice.

A way to get around it is to use the perfromSelector:withObject:afterDelay method as outlined here (I am only allowed to post one hyperlink :( ):http://www.cocoabuilder.com/archive/cocoa/232606-auto-incrementing-integer-attribute-in-awakefrominsert.html.

My working code is now as follows: (note, I have put the bulk of the fetching code used above into a category to tidy it up a little, this allows me to use the method fetchObjectsForEntityName:withPredicate:withFetchLimit:withSortDescriptors:)

- (void) awakeFromInsert
{
[self performSelector:@selector(setIdNumber) withObject:nil afterDelay:0];
self.date = [NSDate date];
}


-(void)setIdNumber
{
int num  = 0;

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"idNumber" ascending:NO];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"idNumber > %@", [NSNumber numberWithInt:0]];

NSArray *array = [[self managedObjectContext] fetchObjectsForEntityName:@"Flight" 
                                                          withPredicate:predicate 
                                                         withFetchLimit:0
                                                    withSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
[sortDescriptor release];   

if (array != nil & array.count != 0)
{
    num = [[[array objectAtIndex:0] valueForKey:@"idNumber"] intValue]; 
} 

num ++;

[self setIdNumber:[NSNumber numberWithInt:num]];
}

Let me know what you think!

One Approach: Create a fetch request of all instances of your entity with a limit of 1, sorted by idNumber to get the highest number.

Another Approach: Keep the highest idNumber in your store's metadata and keep incrementing it.

There are plenty of arguments for and against either. Ultimately, those are the two most common and the choice is yours.

An easier way to do that is to override the newObject method of NSArrayController:

- (id) newObject
{
    id result=[super newObject];
    [result setValue: [NSDate date] forKey: @"date"];
    return result;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!