gpt4 book ai didi

objective-c - 使用异步 NSURLConnection 获取本地文件是否过度?

转载 作者:行者123 更新时间:2023-12-03 16:40:53 25 4
gpt4 key购买 nike

我想从磁盘读取本地 JSON 文件(大约 5,000 多个记录/对象),并且我有此代码并正在尝试使用 Realm

我想在完成加载和解析后更新我的用户界面;我已经尝试了一些变体,但我现在拥有的这个变体似乎有点矫枉过正。

NSURL *url = [[NSBundle mainBundle] URLForResource:fightersFilename withExtension:fightersFileExtension];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:30.0];

NSOperationQueue *queue = [[NSOperationQueue alloc] init];

[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (!error && data) {
//call a delegate to send the data to your page from where it was called

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

dispatch_async(queue, ^{
NSError *error=nil;
NSMutableArray *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];

dispatch_async(dispatch_get_main_queue(), ^{
if (!error) {
// Get realm and table instances for this thread
RLMRealm *realm = [RLMRealm defaultRealm]; // Create realm pointing to default file

[realm beginWriteTransaction];

for (NSDictionary *fighterDict in result) {

DDLogVerbose(@"%@ %@", fighterDict[@"name"], fighterDict[@"filename"]);

Fighter *f = [[Fighter alloc] init];
f.name = fighterDict[@"name"];
f.filename = fighterDict[@"filename"];

[realm addObject:f];
}

// Commit the write transaction
// to make this data available to other threads
[realm commitWriteTransaction];

DDLogVerbose(@"%d fighters in realm", [[Fighter allObjects] count]);
}
});
});

} else {
//show alert that an error has occurred during downloading data from net.
NSLog(@"JSON read error: %@", error);
}
}];

queue=nil;

我的想法是,我想读取 JSON 文件,解析它并将其放入对象中,然后一旦完成,更新我的 UI 或 UX。

鉴于此,上述是一个好的解决方案吗?

最佳答案

你太努力了。

在后台队列的异步调度 block 中,读取文件并同步解析它。完成后,在主队列上触发 after 函数。我将很快编辑它以添加特定代码。

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSURL *url = [[NSBundle mainBundle] URLForResource:fightersFilename
withExtension:fightersFileExtension];
NSAssert(url!=nil, @"URL not found for target resource.");
NSData *data = [NSData dataWithContentsOfURL:url];
NSAssert(data!=nil, @"Reading data file failed.");
NSError *parseError = nil;
NSMutableArray *result = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&parseError];
//TODO: Handle this sanely
NSAssert(parseError==nil, @"Parsing JSON object failed.");
dispatch_async(dispatch_get_main_queue(), ^{
[self didFinishLoadingResource:result];
});
});

关于objective-c - 使用异步 NSURLConnection 获取本地文件是否过度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26392568/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com