【发布时间】:2011-05-09 21:39:37
【问题描述】:
作为 Objective-c 及其内存管理技术的新手,比较以下两部分。 (原代码来自apple.com autorelease pools)
问题:
1. 两片能达到同样的效果吗?
2. 两块内存管理的结果是一样的吗? (至于内存清理、泄漏等)
3. 下面的第二个代码是否违反了最佳实践?性能?
void main()
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSArray *args = [[NSProcessInfo processInfo] arguments];
for (NSString *fileName in args) {
NSAutoreleasePool *loopPool = [[NSAutoreleasePool alloc] init];
NSError *error = nil;
NSString *fileContents = [[[NSString alloc] initWithContentsOfFile:fileName
encoding:NSUTF8StringEncoding error:&error] autorelease];
/* Process the string, creating and autoreleasing more objects. */
[loopPool drain];
}
/* Do whatever cleanup is needed. */
[pool drain];
exit (EXIT_SUCCESS);
}
void main()
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSArray *args = [[NSProcessInfo processInfo] arguments];
NSString *fileContents = [[NSString alloc] autorelease];
for (NSString *fileName in args)
{
// NSAutoreleasePool *loopPool = [[NSAutoreleasePool alloc] init];
NSError *error = nil;
fileContents = [fileContents initWithContentsOfFile:fileName encoding:NSUTF8StringEncoding error:&error];
/* Process the string, creating and autoreleasing more objects. */
//[loopPool drain];
}
/* Do whatever cleanup is needed. */
[pool drain];
exit (EXIT_SUCCESS);
}
【问题讨论】:
-
第二个绝对是非常规的,而且很可能是错误的;您分配一块内存,使用该内存初始化一个对象,将内存标记为释放,然后再次使用它来初始化一个新对象,在重新标记它的过程中。
-
@Josh,不是这样 - 他正在做的很好。除了变量之外没有任何东西被重用,它只是在每次迭代时指向不同的内存位置。
-
我在第 2 部分中为 fileContents 放置“自动释放”的位置出错。我编辑了代码以反映更改。
-
第二个例子仍然不正确——你不能用
+alloc创建一个对象,然后重复调用它的-init方法之一。您必须每次都将+alloc和-init...作为一对呼叫在一起。 -
正如 Sherm 所说,第二个例子是完全错误的。这种模式毫无意义。
标签: objective-c memory-management