wrapper method in extended NSManagedObject class objective-c
I am using CoreData in an iOS application. Everything works fine except for fields marked as Boolean in xcdatamodel that get modeled and NSNumber. For this kind of fields I want to write some utility method in extended class, but I was wondering where's the best location for writing them or what's the best practice.
In MyManagedObject.h I have:
@interface MyManagedObject : NSManagedObject {
@private
}
@property (nonatomic, retain) NSNumber * mandatory;
@end
Where mandatory is a boolean in data model. This is the generated class from xcode:
@implementation MyManagedObject
@dynamic mandatory;
At this point, for properly using the entity I need to write somewhere some utility wrapper methods, probably in the entity itself开发者_如何转开发, such as:
[myManagedObject mandatoryWrapper:YES];
-(void)mandatoryWrapper:(BOOL)mandatory {
// convert boolean to number
self.mandatory=convertedMandatory;
}
But I am aiming to use the original getter/setter for not generating "confusion":
// setter
myManagedObject.mandatory=YES;
//getter
if(myManagedObject.isMandatory)
but I suppose that rewriting the original methods, will cause some problem later on in the application lifecycle, for example when saving or retrieving in context.
thanks.
If you want a true boolean property, then your are forced to change the name. I would recommend just making the it a property of the class and not the entity because the entity doesn't have to know about them.
In your case, you would need something like:
@property BOOL isMandatory;
-(BOOL) isMandatory{
return [self.mandatory boolValue];
}
-(void) setIsMandatory:(BOOL) boolVal{
self.mandatory=[NSNumber numberWithBool:boolVal];
}
This lets you use convience constructions like:
If (self.isMandtaory)...
self.isMandatory=YES;
Core Data is happy because the entity modeled NSNumber property is still there and works as expected but the human can use the easier to comprehend boolean version.
精彩评论