Reputation: 898
I have a fairly involved managed data model which has a central object with many relationships which depend on the values of various attributes. I am importing the initial data into the model using sets of plists, each plist specifying attributes for an entity class and then filling in the relationships based on those attributes.
I wanted to modify the getter for the relationships to automagically fetch objects constrained by an attribute. The reasoning here was to move the relationship building into the managed object and out of the importation logic, but I wasn't able to make that fly eg:
Hypothetical SubclassedManagedObject.m:
-1 #import "SubclassedManagedObject.h'
0 #import "OtherManagedObject.h"
1 @implementation SubclassedManagedObject
2 @dynamic attr1
3 @dynamic relation1 // which is an OtherManagedObject
4 - (OtherManagedObject *)relation1
5 {
6 if( relation1 != nil)
7 return relation1;
8 NSFetchRequest *request = [[NSFetchRequest alloc] init];
9 [request setEntity://the OtherManagedObject entity];
A [request setPredicate://predicate based on attr1];
B NSArray *results;
C results = [[self managedObjectContext] executeFetchRequest:request//..];
D if( [results count] )
E relation1 = [results objectAtIndex:0];
F }
This blew up when compiling at line 6 with:
error: 'relation1' undeclared (first use in this function)
and at line A where building the predicate based on the value of attr1:
error: 'attr1' undeclared (first use in this function)
My question is what I want to do possible or more likely, is there a better way to accomplish this?
Upvotes: 2
Views: 2202
Reputation: 578
thanks Erik, 10 years later and the documentation is down. Here's the swift (computed property) code I came up with
var irregularUses: [IrregularUse]? {
get {
let fetchRequest = NSFetchRequest<MIrregularUse>(entityName: "MIrregularUse")
guard let managedUses = try! managedObjectContext?.fetch(fetchRequest) else { return nil }
return managedUses.map(IrregularUse.init(managed:))
}
}
IrregularUse is a struct, MIrregularUse is its NSManagedObject equivalent. I'm not sure if I need to set a predicate, it seems to work OK without.
Upvotes: 1
Reputation: 898
Well this is awkward. I found the answer to my question in Apple's documentation.
So the implementation of relation1's getter changes to:
- (OtherManagedClass *)relation1
{
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:// the entity];
[request setPredicate:// predicate using attr1];
NSArray *results
results = [[self managedObjectContext] executeFetchRequest:// ...];
if( [results count] )
return [results objectAtIndex:0];
return nil;
}
My mistake was treating the attributes as conventional ivars.
Upvotes: 3