如果您的评论应该是您的 coreDataModel 中的关系,请使用而不是并将其与餐厅实体连接NSMutableArray
。NSSet
回顾:
在餐厅:
如果您让 xcode 生成您的类,它将如下所示:
Restaurant:
@interface Restaurant : NSManagedObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSSet *user_reviews; /* One to Many Relation to Review Entity*/
@interface Restaurant(CoreDataGeneratedAccessors)
- (void)addUser_reviewsObject:(Review *)value;
- (void)removeUser_reviewsObject:(Review *)value;
- (void)addUser_reviews:(NSSet *)value;
- (void)removeUser_reviews:(NSSet *)value;
@end
Review:
@interface Review : NSManagedObject
@property (nonatomic, strong) NSString *rating;
@property (nonatomic, strong) NSString *review_text;
@property (nonatomic, strong) User *user;
@property (nonatomic, strong) Restaurant *restaurant;
@end
您的电话将是:
NSManagedObjectContext *context = [self managedObjectContext];
Restaurant *rest = [NSEntityDescription insertNewObjectForEntityForName:@"Restaurant" inManagedObjectContext:context];
rest.name = restaurant.name;
Review *rev = [NSEntityDescription insertNewObjectForEntityForName:@"Review" inManagedObjectContext:context];
rev.rating = @"1";
rev.review_text = @"nomnomnom";
[rest addUser_reviewsObject:rev];
// or rev.restaurant = restaurant; one of both is enought as far as I remember
// save your context
编辑
如果它必须是 a NSMutableArray
,它就不能是一个 ration。
那些总是NSSets
(如果 x 到 n)或目标类。使用NSMutableArray
利用了集合和自动处理的优点。
但是如果你真的想存储,我建议至少通过一个属性(唯一)NSMutableArray
扩展你的类并将存储为Review
reviewID
NSMutableArray
Transformable
//Review:
@interface Review : NSManagedObject
@property (nonatomic, strong) NSString *rating;
@property (nonatomic, strong) NSString *review_text;
@property (nonatomic, strong) User *user;
@property (nonatomic, strong) NSNumber *reviewID;
@end
//Restaurant.h:
@interface Restaurant : NSManagedObject
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSSet *user_reviews; // Set of NSNumbers
- (void)addUser_reviewsObject:(Review *)value;
- (void)addUser_reviewsID:(NSNumber *)value;
- (void)removeUser_reviewsObject:(Review *)value;
- (void)addUser_reviews:(NSMutableArray *)value;
- (void)removeUser_reviews:(NSMutableArray *)value;
@end
//Restaurant.m:
- (void)addUser_reviewsObject:(Review *)value
{
[self addUser_reviewsID:value.reviewID];
}
- (void)addUser_reviewsID:(NSNumber *)value
{
if(![self.user_reviews containsObject:value];
[self.user_reviews addObject:value];
}
- (void)removeUser_reviewsObject:(NSNumber *)value
{
// follow upper logic and implement yourself
}
- (void)addUser_reviews:(NSMutableArray *)value
{
// follow upper logic and implement yourself
}
- (void)removeUser_reviews:(NSMutableArray *)value
{
// follow upper logic and implement yourself
}