使用coredata在xcode 4.2中插入多对多的关系

时间:2011-12-28 12:02:13

标签: core-data insert many-to-many xcode4.2

嗨我试图插入多对多关系但失败=(

这是代码

categoria.h

#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>

@class SubCategoria;

@interface Categoria : NSManagedObject

@property (nonatomic, retain) NSNumber * id;
@property (nonatomic, retain) NSString * nombre;
@property (nonatomic, retain) NSSet *subcategoria;
@end

@interface Categoria (CoreDataGeneratedAccessors)

- (void)addSubcategoriaObject:(SubCategoria *)value;
- (void)removeSubcategoriaObject:(SubCategoria *)value;
- (void)addSubcategoria:(NSSet *)values;
- (void)removeSubcategoria:(NSSet *)values;

@end

categoria.m

#import "Categoria.h"
#import "SubCategoria.h"


@implementation Categoria

@dynamic id;
@dynamic nombre;
@dynamic subcategoria;

@end

然后我尝试按以下方式插入。

 NSManagedObjectContext *context = [self managedObjectContext];
    Categoria *cat = [NSEntityDescription
                                      insertNewObjectForEntityForName:@"Categoria" 
                                      inManagedObjectContext:context];

    cat.id =[NSNumber numberWithInt:2];
    cat.nombre = @"portatil";




    SubCategoria *subCat =  [NSEntityDescription
                             insertNewObjectForEntityForName:@"SubCategoria" 
                             inManagedObjectContext:context];
    subCat.id = [NSNumber numberWithInt:1];
    subCat.nombre = @"toshiba";

    SubCategoria *subCat2 = [NSEntityDescription
                             insertNewObjectForEntityForName:@"SubCategoria" 
                             inManagedObjectContext:context];

    subCat2.id =[NSNumber numberWithInt:1];
    subCat2.nombre = @"sony";



    [cat addSubcategoriaObject:subCat];


     [cat addSubcategoriaObject:subCat2];

  NSError *error;
    if (![context save:&error]) {
        NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
    }

它插入类别和子类别,但当它试图插入关系时,请给我这个例外。

 -[Categoria subcategoria]: unrecognized selector sent to instance 0x6dd8290

为什么会发生这种错误????? 非常感谢你提前做好准备。

1 个答案:

答案 0 :(得分:1)

听起来您的Categoria实体没有subcategoria属性。仔细检查你的模型。也许你错了什么。

在您的代码中,

是什么
NSLog(@"%@", cat);

输出