gpt4 book ai didi

iphone - 共享资源访问+ UI更新的GCD模式?

转载 作者:行者123 更新时间:2023-11-29 11:08:34 25 4
gpt4 key购买 nike

伙计们!我正在我的应用程序中实现共享缓存。这个想法是在后台从网络中获取缓存数据,然后用新获取的数据更新缓存和 UI。诀窍当然是确保线程安全,因为主线程将持续使用缓存。我不想在其他人可能正在使用缓存时以任何方式修改它。

据我所知,使用@synchronized 来锁定对共享资源的访问并不是 ObjectiveC 中最优雅的方法,因为它会陷入内核,因此相当缓慢。我一直在读到,使用 GCD 是一个很好的选择(让我们暂时忽略它的近亲 NSOperation),我想弄清楚适合我的情况的模式是什么。下面是一些示例代码:

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

// download the data in a background thread
dispatch_async(queue, ^{
CacheData *data = [Downloader getLatestData];

// use the downloaded data in the main thread
dispatch_sync(dispatch_get_main_queue(), ^{
[AppCache updateCache:data];
[[NSNotificationCenter defaultCenter] postNotificationName:@"CacheUpdated" object:nil];
});
});
  1. 这真的会像我认为的那样吗?如果是这样,这是目前处理这种情况的最干净的方法吗?有一个 blog post这与我所说的非常接近,但我也想与您核实一下。
  2. 我在想,只要我只在同一个线程/队列(在我的例子中是 main)上访问共享共享资源,并且只在 main 上更新 UI,那么我将有效地实现线程安全。对吗?

谢谢!

最佳答案

是的。抛开其他考虑因素,不要将读/写工作分流到主线程,而是考虑使用私有(private)调度队列。

dispatch_queue_t readwritequeue;
readwritequeue = dispatch_queue_create("com.myApp.cacheAccessQueue", NULL);

然后更新您的 AppCache 类:

- (void)updateCache:(id)data {
dispatch_sync(readwritequeue, ^{ ... code to set data ... });
}

- (id)fetchData:... {
__block id data = nil;
dispatch_sync(readwritequeue, ^{ data = ... code to fetch data ...});
return data;
}

然后更新您的原始代码:

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

// download the data in a background thread
dispatch_async(queue, ^{
CacheData *data = [Downloader getLatestData];
**[AppCache updateCache:data];**

// use the downloaded data in the main thread
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:@"CacheUpdated" object:nil];
});
});

关于iphone - 共享资源访问+ UI更新的GCD模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12636118/

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