是的,该代码有问题。它过早释放 imgView 可能会在极少数情况下导致崩溃将对象存储在实例变量中而不保留它,而且它通常只是以错误的方式进行内存管理。
一种正确的方法是:
@interface SomeViewController : UIViewController
{
UIImageView *imgView;
}
@property (nonatomic, retain) UIImageView *imgView;
并在实施中;
@synthesize imgView;
模块中的某处:
//Create a new image view object and store it in a local variable (retain count 1)
UIImageView *newImgView = [[UIImageView alloc] initWithFrame:self.view.bounds];
newImgView.image = [UIImage imageNamed:@"someimage.png"];
//Use our property to store our new image view as an instance variable,
//if an old value of imgView exists, it will be released by generated method,
//and our newImgView gets retained (retain count 2)
self.imgView = newImgView;
//Release local variable, since the new UIImageView is safely stored in the
//imgView instance variable. (retain count 1)
[newImgView release];
//Add the new imgView to main view, it's retain count will be incremented,
//and the UIImageView will remain in memory until it is released by both the
//main view and this controller. (retain count 2)
[self.view addSubview:self.imgView];
并且 dealloc 保持不变:
- (void) dealloc
{
[imgView release];
[super dealloc];
}