在使用NSOperationQueue并尝试更改滑块/拾取器等时遇到iphone设备上的大量泄漏

zam*_*ono 5 iphone memory-leaks instruments nsoperationqueue nsautoreleasepool

在使用NSOperationQueue并尝试更改滑块/拾取器等时遇到iphone设备上的大量泄漏

我能够毫无问题地更改标签,但如果我尝试更改在界面构建器上创建的滑块或选取器,我会收到这些泄漏.

Leaked Object   #   Address Size    Responsible Library         Responsible Frame
GeneralBlock-16     0x1b00a0    16  GraphicsServices    GetFontNames
GeneralBlock-16     0x1aea90    16  WebCore                WebThreadCurrentContext
GeneralBlock-16     0x1aea80    16  GraphicsServices    GSFontGetFamilyName
GeneralBlock-64     0x1a7370    64  UIKit                  GetContextStack
Run Code Online (Sandbox Code Playgroud)

代码如下

- (void)loadData {

    NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self
                                                                            selector:@selector(firstRun)
                                                                              object:nil];

    [queue_ addOperation:operation];
    [operation release];
}

- (void)firstRun {

    NSAutoreleasePool *pool = [NSAutoreleasePool new];

    [self setSliders];

    NSLog(@"firstRun method end");

    [pool drain];

}

- (void)setSliders {  

    NSMutableArray *tempArray = [[[NSMutableArray alloc]init] autorelease];
    aquaplannerAppDelegate *appDelegate = (aquaplannerAppDelegate *)[[UIApplication sharedApplication] delegate];
    tempArray = appDelegate.settingsValuesArray;

    freshMarineSegment.selectedSegmentIndex = [[tempArray objectAtIndex:0]intValue];

    for (int i = 1; i <= 20; i++ ) {
        UILabel *label = (UILabel *)[self.view viewWithTag:200+i];  // gets label based on tag  
        UISlider *slider = (UISlider *)[self.view viewWithTag:100+i];  // gets slider based on tag

        slider.value = [[tempArray objectAtIndex:i]intValue];
        label.text = [[[NSString alloc] initWithFormat:@"%@",[tempArray objectAtIndex:i]] autorelease];

        [label release];
        [slider release];
    }
}
Run Code Online (Sandbox Code Playgroud)

Nat*_*ror 7

我假设你在setSliders创建NSOperation 之前正在做其他事情,你只是省略了那些代码.

UIKit不保证是线程安全的,您只应访问主线程上的接口元素.在文档的一些地方提到了这一点,但最有说服力的是Cocoa基础指南:

所有UIKit对象只应在主线程上使用.

所以firstRun应该看起来更像这样:

- (void)firstRun {

  NSAutoreleasePool *pool = [NSAutoreleasePool new];

  // Do something important here...

  [self performSelectorOnMainThread:@selector(setSliders) withObject:nil waitUntilDone:NO];

  NSLog(@"firstRun method end");

  [pool drain];

}
Run Code Online (Sandbox Code Playgroud)

你为什么使用NSMutableArrayin setSliders?你永远不会真正改变数组,可变数据结构会对线程编程造成严重破坏.

另外,我将setSliders方法重命名为updateSliders.这是一个可可风格的问题.以"set"开头的方法应该用于改变单个实例变量/属性.