开发者

NSAutoreleasePool and class variables

开发者 https://www.devze.com 2023-04-10 18:14 出处:网络
I\'m getting what looks like a crash due to overreleasing but as far as I can tell I\'m not doing anything wrong, however I may have the wrong idea about AutoreleasePools and class variables.

I'm getting what looks like a crash due to overreleasing but as far as I can tell I'm not doing anything wrong, however I may have the wrong idea about AutoreleasePools and class variables.

If I have a class variable:

UIImageView *imageView;

and I allocate it in a thread like so:

 - (void)setupThreaded {
     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

     UIImage *image = [UIImage imageNamed:@"myimage.png"];
     imageView = [[UIImageView alloc] initWithImage:image];

     [self performSelectorOnMainThread:@selector(addViewOnMain开发者_运维问答Thread) withObject:nil waitUntilDone:YES];

     [pool release];
}

- (void)addViewOnMainThread {
    [self.view addSubView:imageView];
}

I'm currently occasionally getting an error suggesting that either imageView was prematurely released OR that imageView's image is getting prematurely released.

What could be causing that?


It is extremely unusual to store a view in a class variable. Why are you doing this?

It is, in general, illegal to access UIView on background threads. The docs are a little dodgy on whether construction of a UIView is legal on a background thread, but once you dive into initWithImage:, it definitely is not explicitly supported and is probably not allowed.

If there is some reason you're creating the UIImage on a background thread, that's fine, but then just pass the UIImage itself to the main thread and create the view there. You don't need a class variable to pass it between the threads. Just pass it as the object to performSelectorOnMainThread:withObject.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号