无法在 sharkORM 中使用一对多关系

Not able to use one-to-many relationship in sharkORM

我正在使用 KeyValueObjectMapping 将 JSON 字符串转换为模型 class。

这里是 JSON 字符串:

{
"id_str": "123456",
"name": "Some Name",
"protected": false,
"created_at": "Tue Mar 31 18:01:12 +0000 2009",
    "tweets" : [
        {
            "created_at" : "Sat Apr 14 00:20:07 +0000 2012",
            "id_str" : 190957570511478784,
            "text" : "Tweet text",
            "comments": {
                         "id_str":"2343",
                         "text":"This is comment1"
            }
        },
        {
            "created_at" : "Sat Apr 14 00:20:07 +0000 2012",
            "id_str" : 190957570511478784,
            "text" : "Tweet text",
            "comments": {
                         "id_str":"2343",
                         "text":"This is comment2"
            }
        }
    ]
}

我为此创建了模型 classes,如下所示:

对于用户,

@interface User : SRKObject
@property(nonatomic, strong) NSString *idStr;
@property(nonatomic, strong) NSString *name;
@property(nonatomic, strong) BOOL protected;
@property(nonatomic, strong) NSDate *createdAt;

@property(nonatomic, strong) NSArray *tweets;

@end

对于推文,

@interface Tweet : SRKObject

@property(nonatomic, strong) NSString *idStr;
@property(nonatomic, strong) NSString *text;
@property(nonatomic, strong) NSDate *createdAt;
@property(nonatomic, strong) Comments *comments;

@end

评论,

@interface Comments : SRKObject

@property(nonatomic, strong) NSString *idStr;
@property(nonatomic, strong) NSString *text;

@end

它工作得非常好,我收到了阵列中的推文。我收到的推文是 user.tweets.

为了将其保存在数据库中,我使用 SharkORM 作为 ORM。但是在保存时要么崩溃要么根本不保存推文。

这是 repo 中打开的问题(但使用不同的示例)- https://github.com/sharksync/sharkorm/issues/78

崩溃的原因是存储在用户对象中的推文数组的持久性,而不是将它们存储为单独的 class。参见:This

最终你想要得到的是....

@interface Tweet : NSObject

@property(nonatomic, strong) User* user;
@property(nonatomic, strong) NSString *idStr;
@property(nonatomic, strong) NSString *text;
@property(nonatomic, strong) NSDate *createdAt;

@end

因为将所有推文存储在一个数组对象中只会让你很快陷入困境(无需搜索,保存时间会不断增加)。

因此,当您获取 JSON 时,您可以映射第一个 class 没问题,然后迭代创建与用户 class 相关的对象的推文。

关联对象只是将 .user 属性 设置为您已创建或查询的相关用户实体的一种情况。

感谢@Adrian_H的努力。我想出了解决方案并在此处发布。

我在推文和评论模型中添加了以下代码,将推文保存为 NSArray 并将评论保存为模型对象,并且成功了。

- (void)encodeWithCoder:(NSCoder *)aCoder;
-(id)initWithCoder:(NSCoder *)aDecoder;