0

我有一个 iOS 应用程序,我在其中使用 Core Data 进行存储。我有两个实体(“MyEntity”和“OtherEntity”),它们是一对一的关系。两个实体相互关联(即每个实体与另一个实体具有反向关系)。每个实体的一个属性除了相互之间有关系之外,也是另一个实体的主键。

我遇到的问题是我意识到我不应该有一个属性是另一个实体的外键,当实体彼此有关系时,但是我无法通过引用关系来间接检索主键属性,但我可以通过引用我明确设置为另一个实体的主键的属性来检索它:

//NSInteger userId = [testUser.otherEntity.userId integerValue]; --> returns nil
  NSInteger userId = [testUser.userId integerValue]; --> works fine

其中“testUser”是“MyEntity”类型的实例,它是 NSManagedObject 的子类,“otherEntity”是实体的实例,“OtherEntity”与“MyEntity”具有反向关系。

以下是每个实体的属性:

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

@class OtherEntity;

@interface MyEntity : NSManagedObject

@property (nonatomic, strong) NSString * email;
@property (nonatomic, strong) NSNumber * primaryId; //primary key for MyEntity
@property (nonatomic, strong) NSString * metaData;
@property (nonatomic, strong) NSDate * birthDate;
@property (nonatomic, strong) NSString * name;
@property (nonatomic, strong) NSNumber * userId; //this is the primary key for OtherEntity
@property (nonatomic, strong) OtherEntity *otherEntity;

@end

以下是 OtherEntity 的属性:

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

@class MyEntity;

@interface OtherEntity : NSManagedObject

@property (nonatomic, strong) NSString * address;
@property (nonatomic, strong) NSString * city;
@property (nonatomic, strong) NSString * country;
@property (nonatomic, strong) NSString * fax;
@property (nonatomic, strong) NSString * phone;
@property (nonatomic, strong) NSString * postalCode;
@property (nonatomic, strong) NSString * province;
@property (nonatomic, strong) NSNumber * myUserId//primary key of MyEntity
@property (nonatomic, strong) NSNumber * userId;//primary key of Other Entity
@property (nonatomic, strong) MyEntity *myEntity;

@end

我做错了什么?

4

1 回答 1

0

(来自评论:)您没有为 设置关系testUser,因此testUser.otherEntitynil

然后testUser.otherEntity.userId也是nil[testUser.otherEntity.userId integerValue]返回零。

于 2013-10-11T19:44:14.390 回答