【问题标题】:Why not using autorleasepool block does not throw error?为什么不使用 autoreleasepool 块不会抛出错误?
【发布时间】:2012-08-06 11:58:01
【问题描述】:

我知道当我们使用自定义线程来创建对象并使用它们时。我在 iOS 应用程序中尝试了以下代码,它没有抛出任何错误。为什么?

-(void)Sample{

            NSLog(@"Sample");
            NSString *temp= @"asdfasdf";

            NSArray *tempAray = [NSArray arrayWithObject:temp];


            NSLog(@"Print it %@%s",temp,__FUNCTION__);

}

-(void)viewDidLoad{

            [super viewDidLoad];
            [NSThread detachNewThreadSelector:@selector(Sample) toTarget:self withObject:@"NSSstint"];
            // Do any additional setup after loading the view, typically from a nib.
}

编辑:

我知道如果我将自动释放消息传递给对象,我将泄漏内存。 我将以下方法实现用于示例方法调用: 即使现在我也没有收到以下消息:

*** __NSAutoreleaseNoPool(): object 0x167ba4 autoreleased without a pool in place - just leaking ***


 -(void)Sample{

    NSLog(@"Sample");
    NSString *temp=[[NSString alloc] initWithFormat:@"Sample"];

    NSArray *tempAray = [NSArray arrayWithObject:temp];
    [tempAray retain];
    [tempAray autorelease];
    [temp autorelease];


    NSLog(@"Print it %@%s",temp,__FUNCTION__);

}

【问题讨论】:

    标签: objective-c nsthread nsautoreleasepool


    【解决方案1】:

    它不会产生错误,因为它只会为您提供日志消息。如果您在新线程中自动释放对象而不创建自动释放池,您将收到大量消息,例如

    *** __NSAutoreleaseNoPool(): object 0x167ba4 autoreleased without a pool in place - just leaking ***
    

    但这与抛出 NSExcpetion 相同。此外,您可能从中获得的“它运行良好”的印象是错误的:您会泄漏内存,并且您的应用偶尔会因内存不足而崩溃。

    【讨论】:

    • 感谢 H2CO3。我已经更新了我的问题。你能解释一下为什么我没有收到你提到的消息吗?
    猜你喜欢
    • 1970-01-01
    • 2021-12-19
    • 2023-02-04
    • 1970-01-01
    • 2021-05-04
    • 2017-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多