我有 OS X 10.6 SDK 的代码。有一件事我无法理解。
[1]
int main(int argc, const char*argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *strScript =
@"set theURL to \"\" \n"
"tell application \"Safari\" \n"
"set theURL to URL of current tab of window 1 \n"
"end tell \n"
"return theURL \n";
int poolCount = 0;
while(1)
{
poolCount++;
NSAppleScript *script = [[[NSAppleScript alloc] initWithSource:strScript] autorelease];
NSArray *array = [[[script executeAndReturnError:nil] stringValue] componentsSeparatedByString:@" "];
if (array) {
NSLog(@"%@", array);
}
if (poolCount>=100)
{
[pool release];
pool = [[NSAutoreleasePool alloc] init];
poolCount = 0;
}
}
[pool release];
}
在代码中,当 poolCount 为 100 时释放和分配 autoreleasepool。我发现总是存在泄漏。
但是下面的代码没有泄漏。
[2]
int main(int argc, const char*argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *strScript =
@"set theURL to \"\" \n"
"tell application \"Safari\" \n"
"set theURL to URL of current tab of window 1 \n"
"end tell \n"
"return theURL \n";
while(1)
{
NSAutoreleasePool *lpool = [[NSAutoreleasePool alloc] init];
NSAppleScript *script = [[[NSAppleScript alloc] initWithSource:strScript] autorelease];
NSArray *array = [[[script executeAndReturnError:nil] stringValue] componentsSeparatedByString:@" "];
if (array) {
NSLog(@"%@", array);
}
[lpool release];
}
[pool release];
}
内部循环的自动释放池是 [1] 和 [2] 之间的区别。
请让我知道为什么在 [1] 的情况下内存泄漏。