【问题标题】:Insert one object to a many relationship - IOS Core Data将一个对象插入多个关系 - IOS核心数据
【发布时间】:2012-03-26 21:48:07
【问题描述】:

我已经看到各种答案,帮助解释在一对多关系中添加记录,但我似乎无法为我的代码做出头或尾。

我有一个关系 - 国家有很多县

我正在将县添加到已经存在但似乎无法获得将县添加到国家关系的方法...

我的代码是:

@class Country, Property;

@interface County : NSManagedObject

@property (nonatomic, retain) NSNumber * id;
@property (nonatomic, retain) NSDate * last_server_update;
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) Country *country;
@property (nonatomic, retain) NSSet *properties;
@end

@interface County (CoreDataGeneratedAccessors)

- (void)addPropertiesObject:(Property *)value;
- (void)removePropertiesObject:(Property *)value;
- (void)addProperties:(NSSet *)values;
- (void)removeProperties:(NSSet *)values;

@end

国家.h

@class County, Property;

@interface Country : NSManagedObject

@property (nonatomic, retain) NSNumber * id;
@property (nonatomic, retain) NSDate * last_server_update;
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSSet *properties;
@property (nonatomic, retain) County *counties;
@end

@interface Country (CoreDataGeneratedAccessors)

- (void)addPropertiesObject:(Property *)value;
- (void)removePropertiesObject:(Property *)value;
- (void)addProperties:(NSSet *)values;
- (void)removeProperties:(NSSet *)values;

- (void)addCountiesObject:(County *)value;
- (void)removeCountiesObject:(County *)value;
- (void)addCounties:(NSSet *)values;
- (void)removeCounties:(NSSet *)values;

@end

在我的控制器中:

Country * newCounty;
newCounty = [County createEntity];

// Get Country
Country * relatedCountry = [Country findFirstByAttribute:@"id" withValue:[county objectForKey:@"country_id"]];
                 
newCounty.id = [county objectForKey:@"id"];
newCounty.name = [county objectForKey:@"name"];
newCounty.country = relatedCountry;  // Does not compile

顺便说一句,我正在使用 MagicalRecord 作为查找器

编辑

错误 在“国家”类型的对象上找不到属性“国家”

关系设置为

国家

  • 关系:县
  • 目的地:县
  • 逆向:国家
  • 多对多关系:选中

  • 关系:国家/地区
  • 目的地:国家
  • 逆:县
  • 多对多关系:未选中

【问题讨论】:

  • 您说您在最后一行遇到编译器错误...错误信息是什么?这可能会有所帮助。另外,你确定你已经在你的模型中建立了逆向关系吗?最后,您确定relatedCountry 是您所期望的吗? (添加一些 NSLogs 或调试器断点以确保。)
  • 对不起,这个错误会有所帮助......我已经更新了这个问题。

标签: iphone ios core-data one-to-many relationship


【解决方案1】:

尝试改变

Country * newCounty;

County * newCounty;

;)

【讨论】:

  • 谢谢。 +1,000 给我的甜瓜工厂!不敢相信这是这么简单的事情。
  • 您在newCounty = [County createEntity] 行没有收到编译器警告吗?
猜你喜欢
  • 2013-06-05
  • 1970-01-01
  • 2014-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多