[英]Obj-C ARC: How to remove an object from an array/set and then return it as an autoreleased object?
[英]ARC and autoreleased object
我需要一個ViewController進行模態調用,以在當前窗口的頂部顯示一些UIButton和其他UIView。 我希望背景是部分透明的,並在其下方顯示當前窗口-與UIActionSheet類似,但具有自定義設計。 我對VC進行了編碼,以執行以下操作:1)在初始化過程中,VC將self.view.frame設置為[[UIApplication sharedApplication] keyWindow] .frame 2)調用show()時,VC在[ [UIApplication sharedApplication] keyWindow]子視圖3)內部按鈕調用私有方法release()時,VC從其超級視圖中刪除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具有“自給自足”的功能-它在初始化期間存儲一個指向自身的指針,並在准備釋放自己時將其設置為nil。 它可以工作,但是我感覺這違反了ARC設計原則! 這種方法正確嗎? 如果沒有,我該如何處理?
在此先感謝您的幫助。
不能那樣工作。 你沒有提及自我。 在主視圖控制器中,您只需創建您的對象。 如果需要更長的時間,請將其保留在主視圖控制器中的一個屬性中,完成后,在主視圖控制器中將該屬性設置為nil。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.