好了,我走了,和Xcode打了一下,这里发生了什么事情的模型,这似乎符合我所看到的。
我上面使用的块是没有做什么特别的东西,但enumerateObjectsUsingBlock
码似乎有自己的NSAutoreleasePool
,因此这似乎是什么导致dealloc
要对对象alloc'ed
调用,但自动释放块内。
下面的代码的行为符合我所看到的上面:
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
// simple block test - just iterate over some items and
// add them to a string
typedef void (^AccArrayBlock)(id obj, int idx, BOOL *stop);
// items to 'process'
NSArray *items = [NSArray arrayWithObjects:@"why ", @"must ", @"this ",nil];
int idx = 0;
BOOL doStop = NO;
// make sentence mutable, so we can assign it inside block
__block NSString *sentence = @"";
// make a similar block to what we'd pass to enumerate...
AccArrayBlock myBlock = ^(id obj, int idx, BOOL *stop)
{
// returns and assigns an autoreleased string object
sentence = [sentence stringByAppendingFormat:@"(%d) %@ ",idx,obj];
};
// enumerate items and call block
for (NSString *item in items) {
// create a pool to clean up any autoreleased objects in loop
// remove this line, and the sentence will be valid after loop
NSAutoreleasePool *innerPool = [[NSAutoreleasePool alloc] init];
myBlock(item, idx++, &doStop);
// drain the pool, autorelease objects from block
[innerPool drain];
if (doStop) {
break;
}
}
// faults if we drained the pool
// Program received signal: “EXC_BAD_ACCESS”.
NSLog(@"Sentence is %@",sentence);
[pool drain];
return 0;
}
如果我删除innerPool
对象,然后代码工作,因为我原先预期,大概在NSRunLoop
池最终将清理各种NSString
对象。
注:此线程现在是 'enumerateObjectsUsingBlock自动释放' 2号谷歌的结果:
Google 'enumerateObjectsUsingBlock+autorelease'
第一个结果证实了这一答案。谢谢大家。
哇,这是奇怪的,我不知道为什么不起作用。 – jtbandes
我见过人们做了'[someVariable保留]自动释放]'在块的结束返回的东西,但我不知道为什么,应该使任何区别,如果我怀疑,一个自动释放池运行。我不知道,这就是为什么我问,而且有各种关于复制块的文章,并将它们传递给它们,但没有我能找到的应该很简单的东西,就像这样。 –
你得到的错误/异常是什么? – nacho4d