Database Reference
In-Depth Information
-createChildForObject: Implementation
- (byref NSManagedObject*)createChildForObject:(byref NSManagedObject*)parent;
{
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *localParent = [context objectWithID:[parent objectID]];
NSManagedObject *object = nil;
object = [NSEntityDescription insertNewObjectForEntityForName:@
"Child"
inManagedObjectContext:context];
[object setValue:localParent forKey:@
"parent"
];
return
object;
}
The
-createChildForObject:
implementation is similar to the
-createObject
implemen-
tation discussed earlier. There is one important difference, though. Since we
defined the
Child
entity to have a nonoptional
parent
property, we set it immedi-
ately while we are still on the main thread of the server. This again is a
protection against the uncontrollably multithreaded nature of distributed
objects. We could just create the
Child
entity and return it to the caller, but
there is a fair chance that a save will occur before the relationship is updated
on the client, and an error would result.
In addition to setting the
parent
property on the
Child
object, we also grab a
local reference to the passed-in
NSManagedObject
. Although I did not receive any
errors while testing this method by using the remote proxy, there is no reason
to risk it.
-objectsOfName:withPredicate: Implementation
- (byref NSArray*)objectsOfName:(bycopy NSString*)name
withPredicate:(bycopy NSPredicate*)predicate;
{
NSManagedObjectContext *context = [self managedObjectContext];
NSError *error = nil;
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:name
inManagedObjectContext:context]];
[request setPredicate:predicate];
NSArray *results = [context executeFetchRequest:request error:&error];
[request release], request = nil;
if
(error) {
NSLog(@
"%@:%s Error on fetch %@"
, [self class], __PRETTY_FUNCTION__, error);
return
nil;
}
return
results;
}