多线程和自动释放池 [英] Multithreading and autorelease pool
问题描述
当我掌握我的技能与多线程与GCD,我遇到一些问题。假设你有以下方法:
- (void)方法{
NSString * string = [NSString string]; //将被自动释放
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),^ {
//非常非常冗长的操作...
NSLog (@%@,string); //是安全吗?
});
}
我想知道这是否正确,因为我认为我应该保留在块执行之前的字符串:事实上我担心事件循环完成并发送 string
一个autorelease消息,然后使用 string
在块中。这将导致程序崩溃。
我是对吗?是否应该向 string
发送一个retain和一个释放消息,或者这是正确的实现?
提前感谢!
我想知道这是否正确,因为我想我应该在块执行之前保留字符串:事实上,我担心事件循环完成并发送字符串一个autorelease消息在使用字符串在块中。
不要害怕:
块捕获了周围方法/函数的范围,因为它会自动保留
变量,在块内使用。注意,当你在块中使用 self
时,这可能会极大地影响对象的生命周期!
此规则有一个例外,它们是声明为
的变量 __ block SomeObjectPointerType variableName
更新
因为这个答案有新的评论在ARC下所有对象变量默认为 __ strong
,并且在ARC下引入了一些变化:
< 这也适用于标有
__ block
的变量。如果你想避免强制捕获块中的变量,你应该定义一个局部变量 __ weak
。 < h2> End Update
如果你想了解更多关于块的信息,bbum给了一个很好的会话,叫做 介绍块和大中央调度在iPhone上 (iTunes U链接)在WWDC 2010。
块详细信息部分始于11:30。
As I'm mastering my skills with multithreading with GCD, I've come across some question. Suppose you have the following method:
- (void)method {
NSString *string= [NSString string]; //will be autoreleased
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//very very lengthy operation...
NSLog(@"%@", string); //is it safe?
});
}
I'm wondering if this is correct, because I think I should have retained string before the block execution: in fact I fear that the event loop finishes and sends string
an autorelease message before using string
in the block. That would crash the program.
Am I right? Should I send a retain and a release message to string
or this is the correct implementation?
Thanks in advance!
I'm wondering if this is correct, because I think I should have retained string before the block execution: in fact I fear that the event loop finishes and sends string an autorelease message before using string in the block.
Fear not:
A block captures the scope of the surrounding method/function in that it automatically retain
s any object-variable that is used inside of the block. Be aware of that when you use self
inside of a block, as this may greatly affect the lifetime of the object!
There is one exception to this rule, and that are variables declared as
__block SomeObjectPointerType variableName
Update
Because there’s a new comment on this answer, I should probably add that things changed a little with the introduction of ARC:
Under ARC all object variables default to __strong
, and this holds for variables marked with __block
as well. If you want to avoid strong capturing of a variable in a block, you should define a local variable that is __weak
.
End Update
If you like to learn more about blocks, bbum gave an excellent session called Introducing Blocks and Grand Central Dispatch on iPhone (iTunes U link) at WWDC 2010.
The "Block Details" section starts at 11:30.
这篇关于多线程和自动释放池的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!