首页 文章

ARC和自动释放的对象

提问于
浏览
0

我需要一个ViewController以模态方式调用,以在当前窗口的顶部显示一些UIButton和其他UIView . 我希望背景部分透明并显示其下方的当前窗口 - 类似于UIActionSheet但具有自定义设计 . 我编写了VC来执行以下操作:1)在初始化期间,VC将self.view.frame设置为[[UIApplication sharedApplication] keyWindow] .frame 2)当调用show()时,VC将self.view添加到[ [UIApplication sharedApplication] keyWindow] subViews 3)当内部按钮调用私有方法release()时,VC从其superview中删除self.view . 单个释放按钮的示例如下:

@implementation ModalController

- (id)init
{
   self = [super init];
   if (self){
       //set my view frame equal to the keyWindow frame
       self.view.frame = [[UIApplication sharedApplication]keyWindow].frame;
       self.view.backgroundColor = [UIColor colorWithWhite:0.3f alpha:0.5f];

       //create a button to release the current VC with the size of the entire view
       UIButton *releaseMyselfButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
       [releaseMyselfButton setTitle:@"Release" forState:UIControlStateNormal];
       releaseMyselfButton.frame = CGRectMake(0, 0, 90, 20);
       [releaseMyselfButton addTarget:self action:@selector(releaseMyself) forControlEvents:UIControlEventTouchDown];

       //add the button to the view
       [self.view addSubview:releaseMyself];
   }
   return self;
}

- (void) show
{
   //add self.view to the keyWindow to make sure that it will appear on top of everything else
   [[[UIApplication sharedApplication]keyWindow] addSubview:self.view];
}

- (void)releaseMyself
{
    [self.view removeFromSuperview];
}

@end

如果我从另一个VC创建一个ModalController实例,我调用show()一切都按预期进行:

@interface CurrentVC ()
   @property (strong, nonatomic) ModalController *myModalController;
@end

@implementation CurrentVC
   - (void)viewDidLoad
   {
      [super viewDidLoad];
      self.myModalController = [[ModalController alloc]init];
      [self.myModalController show];
   }
@end

为了使它工作,我需要在属性中保留ModalController,直到调用release() . 但是,我想拥有与UIActionSheet相同的自由,只需将其实例保存在局部变量中:

@implementation CurrentVC
   - (void)viewDidLoad
   {
      [super viewDidLoad];
      ModalController *myModalController = [[ModalController alloc]init];
      [myModalController show];
   }
@end

如果我使用当前代码执行此操作,ARC将在调用show()之后直接释放myModalController,并且释放按钮将指向nil . 如何在不将对象存储在属性中的情况下完成此工作?我已经找到了解决方法,但我不确定这是一个很好的设计选择:

@interface ModalController ()
   @property (strong, nonatomic) ModalController *myselfToAutorelease;

@implementation ModalController

- (id)init
{
   self = [super init];
   if (self){
       ... ... ...
       self.myselfToAutorelease = self;
   }
   return self;
}

- (void) show
{
   ... ... ...
}

- (void)releaseMyself
{
    [self.view removeFromSuperview];
    self.myselfToAutorelease = nil;
}

我所做的是让ModalController“自给自足” - 它在init期间存储一个指向自身的指针,并在它准备释放自己时将其设置为nil . 它有效,但我觉得这违反了ARC的设计原则!这种方法是否正确?如果没有,我该如何区别对待?

在此先感谢您的帮助 .

1 回答

  • 0

    不是这样的 . 你没有提到自我 . 在主视图控制器中,您只需创建对象 . 如果需要将其保存在较长时间,请将其保存在主视图控制器的属性中,完成后,在主视图控制器中将该属性设置为nil .

相关问题