ios - 无法在 SharkORM 中使用一对多关系

标签 ios json orm model key-value

我正在使用 KeyValueObjectMapping 将 JSON 字符串转换为 Model 类。

这是 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"
            }
        }
    ]
}

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

对于用户,
@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

最佳答案

崩溃的原因是存储在用户对象中的推文数组的持久性,而不是将它们存储为单独的类。见: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 时,您可以毫无问题地映射第一个类,然后迭代推文创建与 User 类相关的对象。

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

关于ios - 无法在 SharkORM 中使用一对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43320601/

相关文章:

ios - 嵌套 GLKViewController

ios - 快速检查网络速度

javascript - 并非所有 Ajax 内容都加载在一个域上

android - 为什么 futureBuilder 有时会卡在进度加载器上?

java - JPA继承建模问题

ios - 访问应用程序文件夹 iOS

ios - 尝试将 Crashlytics 更新到 v3.10.3 时没有此类模块错误

json - 如何告诉 Grails 将 JSONNull 呈现为 null?

django - 如何避免在 Django 中进行 n+1 选择?

php - 名为 “db2” 的 Symfony2 Doctrine ORM 管理器不存在