简体   繁体   中英

Should you asynchronously store images in Realm iOS?

I am currently using Realm for data persistence within an app I am creating.

What I am trying to do is that when the app is first opened, it fetches data from an 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. I am also curious to know if this is bad practice.

Cheers

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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