views:

958

answers:

1

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?

+2  A: 

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.

Erik