I have the following factory method. I'm just wondering if the assignment
self = [NSEntityDescription insertNewObjectForEntityForName:entityName
inManagedObjectContext:[self managedObjectContext]];
is correct, given the fact that my class is a subclass of NSManagedObject
thanks
+ (CBItem *)insertEntityForName:(NSString*)entityName fromXMLElement:(NSXMLElement*)xmlElement with开发者_开发问答QueryType:(CBSearchQueryType)queryType inContext:(NSManagedObjectContext *)inContext
...
self = [NSEntityDescription insertNewObjectForEntityForName:entityName
inManagedObjectContext:[self managedObjectContext]];
...
return self;
No, this is not correct. You only assign to self
inside an init
method. For a factory type method, you should be returning a variable, e.g.
CBItem* newItem = [NSEntityDescription insertNewObjectForEntityForName:entityName inManagedObjectContext:[self managedObjectContext]];
//Other stuff
return newItem;
self in a class method (declared with + instead of -) refers to the class object. Though, once within any method, self is like a local variable. You can reassign it to anything you want, as long as you don't expect it to continue to act like self is normally supposed to. So what you were doing will not be broken, though it is potentially confusing.
精彩评论