简体   繁体   English

您是否应该在Realm iOS中异步存储图像?

[英]Should you asynchronously store images in Realm iOS?

I am currently using Realm for data persistence within an app I am creating. 我目前正在使用Realm在我创建的应用程序中实现数据持久性。

What I am trying to do is that when the app is first opened, it fetches data from an api. 我想做的是,当应用程序首次打开时,它会从api中获取数据。 I want to get all the content from that data fetched and store it so the app can be used even if there is no active internet connection. 我想从该数据中获取所有内容并进行存储,以便即使没有活动的互联网连接也可以使用该应用程序。

I can however achieve storing strings like username and mobile number but I am not sure how to store images. 但是,我可以实现存储诸如用户名和手机号码之类的字符串,但是我不确定如何存储图像。

This is what I have so far: 这是我到目前为止的内容:

@interface User : RLMObject

@property NSString *userName;
@property NSString *mobileNumber;
@property NSData *avatarData;

@end


- (void)viewDidLoad {
    [super viewDidLoad];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:[NSString stringWithFormat:@"%@users?auth_token=%@",BASE_URL,AUTHENTICATION_TOKEN]parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

        [self storeFetchedData: responseObject];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    }];

}

- (void)storeFetchedData:(NSDictionary *)list {
    RLMRealm *realm = [RLMRealm defaultRealm];
    [realm beginWriteTransaction];

    for (id slUser in list) {
        User *user = [[User alloc] init];
        user.userName = slUser[@"name"];
        user.realName = slUser[@"mobileNumber"];

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){

            user.avatarData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString:slUser[@"image_url"]]];

        });
    }

    [realm commitWriteTransaction];

}

[self.tableView reloadData];

I am not new to iOS but this is my first time using realm or such However, I suspect thread problems as the commit is done on the main thread. 我对iOS并不陌生,但这是我第一次使用realm或诸如此类。但是,我怀疑线程问题是因为在主线程上完成了提交。 I am also curious to know if this is bad practice. 我也很好奇这是否是不好的做法。

Cheers 干杯

虽然您可以将图像作为NSData属性存储在Realm中,但是我建议将图像写出到磁盘上,或者使用Pinterest的PINCache之类的东西 ,然后将路径/密钥作为字符串属性存储在Realm中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM