Rabu, 01 Juli 2009

Core Data - Determining if a Managed Object is New

Sorry for the dearth of OpenGL ES posts. Things are quite hectic now with writing More iPhone Development, and I'm not even fully caught up from the week spent at WWDC. So, it may be a little while before I'm able to get another substantive post out like another OpenGL ES tutorial.

Anyone working with Core Data may appreciate this short category I wrote, with some help from Jim Dovey. Curiously enough, managed objects don't know if they are new or not. That is to say, whether they've been added to the context since the last load or save. I've found this to be a piece of information I've needed a lot, so wrapped up the check into a category.

NSManagedObject-isNew.h

//
// NSManagedObject-IsNew.h

#import <Foundation/Foundation.h>


@interface NSManagedObject(IsNew)
/*!
@method isNew
@abstract Returns YES if this managed object is new and has not yet been saved yet into the persistent store.
*/

-(BOOL)isNew;
@end



NSManagedObject-isNew.m

//
// NSManagedObject-IsNew.m
//

#import "NSManagedObject-IsNew.h"


@implementation NSManagedObject(IsNew)
-(BOOL)isNew
{
NSDictionary *vals = [self committedValuesForKeys:nil];
return [vals count] == 0;
}

@end



Then you can just add these files to your project, #import the header file, and then you can ask any managed object if it's new by sending it an isNew message.

0 komentar:

Posting Komentar

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Lady Gaga, Salman Khan