0

EDIT: For one I suppose I shouldn't make an instance method of this kind but make it a class method!? Another thing, I added the fetch method to class C, which works. I'm just thinking that it would be convenient if one could access the data store through the managed objects, but I suppose that somewhat goes against the ideas behind managedObjectContext, persistence and so on?


I'm not sure if I'm trying to do something you're not supposed to do but here goes.

I have a data model with an entity A having a relationship to entity B (B to many A). I have a number of entities of type B in the data store, and now I would like to create a number of entities of type A. In order to do so I need to get references to the entities of type B, i.e., I have to query the data store. I do as follows in a B category, i.e.:

#import "B+Helper.h"

@dynamic managedObjectContext;

@implementation B (Helper)

- (Store *)getBByRef:(NSString *)ref
{
    NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"B" inManagedObjectContext:self.managedObjectContext];
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity:entityDescription];

    NSPredicate *predicate = [NSPredicate predicateWithFormat: @"ref == %@", ref];
    [request setPredicate:predicate];

    NSError *error = nil;
    NSArray *storeArray = [self.managedObjectContext executeFetchRequest:request error:&error];
    NSInteger bCount = [bArray count];
    if ( bCount > 1 || bCount == 0) {
        // Deal with error...
    } else {
        return [bArray objectAtIndex:0];
    }
}

Now, the problem is that I cannot seem to set the managedObjectContext correctly---I get the error:

CoreData: error: Failed to call designated initializer on NSManagedObject class 'B'

I tried passing the managedObjectContext from AppDelegate to the class C having to fetch the B entities and from class C to class B+Helper before calling the method stated above, but that didn't work.

Basically, I just want to be able to make a core date query from a simple NSObject class or a NSManagedObject extension, i.e., from a class which is not a UIViewController of some sort.

In class C I did as follows:

B *b = [[B alloc] init];
b.managedObjectContext = self.managedObjectContext;

But then I get an error saying the selector is absent:

setManagedObjectContext:]: unrecognized selector sent to instance...

I hope it makes sense?!

4

1 に答える 1

0

本当に、インスタンス メソッドでカテゴリを作成する代わりに、既に作成したメソッドを、生成された B エンティティ クラスの実装とインターフェイスに追加するだけです。

+ (Store *)getBByRef:(NSString *)ref;

そして、それはうまくいくはずです。

于 2012-04-12T23:59:23.130 に答える