【问题标题】:Xcode Objective C - Help with NSAutoreleaseNoPool error using NSThreadXcode Objective C - 使用 NSThread 帮助解决 NSAutoreleaseNoPool 错误
【发布时间】:2011-07-23 02:25:06
【问题描述】:

各位专家,我在使用 NSThread 时遇到了一点问题。 Xcode 不断给我“* __NSAutoreleaseNoPool(): Object 0x5694dc0 of class NSCFString autoreleased with no pool in place - just leaking”错误。

我用这条线正确地声明了池 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

然后在我的循环结束时,我使用: [池释放];

是因为我使用委托方法作为 performSelectorInBackground 吗? 感谢stackoverflow。

    - (void)preFetch { //process filenames to be downloaded and assign types to each one
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    NSArray *regions = [NSArray arrayWithObjects: @"dr_national", @"ds_ir", @"conus_FL360", @"FL360_conus", @"dr_nw", @"dr_nc", @"dr_ne", @"dr_sw", @"dr_sc", @"dr_se", @"ds_ir_nw", @"ds_ir_nc", @"ds_ir_ne", @"ds_ir_sw", @"ds_ir_sc", @"ds_ir_se", nil];
    NSError* error;
    for (NSString *regionDir in regions) {
        NSLog(@"region now: %@", regionDir); foo = 0;
        NSString *regUrl = [NSString stringWithFormat:@"http://someUrl/%@/index.lst", regionDir ];
        NSString* text1 = [NSString stringWithContentsOfURL:[NSURL URLWithString:regUrl ] encoding:NSASCIIStringEncoding error:&error];
        NSArray *listItems = [text1 componentsSeparatedByString:@"\n"];
        for (int k=0; k<[listItems count]; k++) {
            if ([[listItems objectAtIndex:k] length] != 0){
                NSString *newpath = [NSString stringWithFormat:@"http://someUrl/%@", [listItems objectAtIndex:k]];
                NSLog(@"newpath: %@",newpath);
                [self performSelectorInBackground:@selector(moveProgressBar) withObject:nil];
                [self fetchImages:newpath:type]; //pass multiple arguments to fetchImages, newpath and type
            }
        }
    }
    [pool release];
}

    - (void)moveProgressBar{
        [delegate increaseAmount];
    }

【问题讨论】:

    标签: objective-c xcode nsthread nsautoreleasepool


    【解决方案1】:

    你应该在你的方法中设置一个自动释放池,因为它是在不同的线程上调用的。

    - (void)moveProgressBar
    {
         NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
         [delegate increaseAmount];
         [pool drain];
    }
    

    编辑

    话虽如此,看看代码本身,您似乎正在尝试从后台线程更新 UI?任何这样做的代码都应该在主线程上执行。

    如果您要运行一个长时间运行的进程,该进程不锁定 UI,并让用户随时了解进度,典型的模式是在后台线程上自行处理,并定期更新UI 使用performSelectorOnMainThread:

    【讨论】:

    • 成功了!非常感谢,为此困扰了一段时间。
    • 委托方法increasAmount只是告诉主线程增加进度视图栏,长加载才是正确的主线程。进度视图更新是衍生线程。
    • 所以你在后台线程中调用一个方法,然后在主线程中调用一个方法?好像有点绕。不过,很高兴您解决了问题。
    猜你喜欢
    • 2011-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多