iPhone使用互斥体与异步URL请求 [英] iPhone use of mutexes with asynchronous URL requests

查看:154
本文介绍了iPhone使用互斥体与异步URL请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的iPhone客户端有很多参与异步请求,很多时间不断修改静态字典或数组的集合。因此,我常常看到更大的数据结构,需要更长的时间从服务器检索以下错误:

My iPhone client has a lot of involvement with asynchronous requests, a lot of the time consistently modifying static collections of dictionaries or arrays. As a result, it's common for me to see larger data structures which take longer to retrieve from a server with the following errors:

*** Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection <NSCFArray: 0x3777c0> was mutated while being enumerated.'

这通常意味着两个对服务器的请求返回数据正在尝试修改相同的集合。我正在寻找的是一个教程/示例/了解如何正确地构建我的代码,以避免这个有害的错误。我确实相信正确的答案是互斥,但我从来没有亲自使用它们。

This typically means that two requests to the server come back with data which are trying to modify the same collection. What I'm looking for is a tutorial/example/understanding of how to properly structure my code to avoid this detrimental error. I do believe the correct answer is mutexes, but I've never personally used them yet.

这是使用NSURLConnection异步HTTP请求,然后使用NSNotification Center作为一种请求完成后的委托方式。

This is the result of making asynchronous HTTP requests with NSURLConnection and then using NSNotification Center as a means of delegation once requests are complete. When firing off requests that mutate the same collection sets, we get these collisions.

推荐答案

如果可能发生任何数据(包括类)将同时从两个线程访问你必须采取措施保持这些同步。

If it's possible that any data (including classes) will be accessed from two threads simultaneously you must take steps to keep these synchronized.

幸运的是Objective-C使用synchronized关键字很容易做到这一点。此关键字作为参数任何Objective-C对象。

Fortunately Objective-C makes it ridiculously easy to do this using the synchronized keyword. This keywords takes as an argument any Objective-C object. Any other threads that specify the same object in a synchronized section will halt until the first finishes.

-(void) doSomethingWith:(NSArray*)someArray
 {    
    // the synchronized keyword prevents two threads ever using the same variable
    @synchronized(someArray)
    {
       // modify array
    }
 }

如果您需要保护多个变量,使用表示对该组数据的访问的信号量。

If you need to protect more than just one variable you should consider using a semaphore that represents access to that set of data.

// Get the semaphore.
id groupSemaphore = [Group semaphore];

@synchronized(groupSemaphore) 
{
    // Critical group code.
}

这篇关于iPhone使用互斥体与异步URL请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆