如何在Objective-C中创建实例变量

4

我有一个例子,想把我的图片作为实例变量,以便使用removeFromView。有什么好的想法吗?尝试不同的方法时,我得到了各种警告和错误提示。提前感谢您。

- (void) viewDidLoad
{
   UIImageView *my_Picture = [[UIImageView alloc] initWithImage: myImageRef];
   [self.view addSubview:my_Picture];
   [my_Picture release];

   [super viewDidLoad];
}
1个回答

9

如果要将其变为实例变量,则应将值存储在您的类中,而不是作为临时变量。当您的类被销毁时,您还需要释放它,而不是在将其添加为子视图后释放。

例如:

// header file (.h)
@interface MyController : UIViewController
{
  UIImageView* myPicture;
}
@end

// source file (.m)
- (void) viewDidLoad
{
   myPicture = [[UIImageView alloc] initWithImage: myImageRef];
   [self.view addSubview:myPicture];

   [super viewDidLoad];
}

- (void) dealloc
{
   [myPicture release];
   [super dealloc];
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接