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

时间:2021-06-11 19:58:06

I have this example, and I would like to make my_Picture an instance variable in order to use removeFromView. Any Ideas? I got all kinds of warnings and errors trying different approaches. Thank you in advance

我有这个例子,我想让my_Picture成为一个实例变量,以便使用removeFromView。有任何想法吗?尝试不同的方法时,我得到了各种各样的警告和错误。先感谢您

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

   [super viewDidLoad];
}

1 个解决方案

#1


To make it an instance variable you would store the value in your class instead of as a temporary variable. You will also release it when your class is destroyed instead of after adding it as a subview.

要使其成为实例变量,您可以将值存储在类中而不是临时变量中。当您的类被销毁而不是将其添加为子视图后,您也将释放它。

E.g.

// 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];
}

#1


To make it an instance variable you would store the value in your class instead of as a temporary variable. You will also release it when your class is destroyed instead of after adding it as a subview.

要使其成为实例变量,您可以将值存储在类中而不是临时变量中。当您的类被销毁而不是将其添加为子视图后,您也将释放它。

E.g.

// 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];
}