我需要一個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。與單一的釋放按鈕舉例如下:ARC和自動釋放對象
@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
爲了使它工作,我需要在調用release()之前將ModalController保留在屬性中。不過,我想有同樣的自由我有一個UIActionSheet和簡單地保持它的一個實例在一個局部變量:
@implementation CurrentVC
- (void)viewDidLoad
{
[super viewDidLoad];
ModalController *myModalController = [[ModalController alloc]init];
[myModalController show];
}
@end
如果我這樣做是與當前的代碼ARC展伸直後會釋放myModalController()是調用,釋放按鈕將指向零。如何在不將對象存儲在屬性中的情況下進行此項工作?我已經確定了周圍的工作,但我不知道這是一個很好的設計選項:
@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和設置當它準備好釋放自己時,它就是零。它的工作原理,但我覺得這是違反ARC設計原則!這種方法是否正確?如果不是,我該如何處理這個問題呢?
在此先感謝您的幫助。
謝謝uchuugaka。它對於像UIAlertView或UIActionSheet這樣的類是如何工作的 - 一旦在屏幕上你不需要保存一個指向它們的指針,當按下按鈕時它們將被自動釋放,對嗎?有沒有使用ARC編寫這些類?謝謝。 – tanzolone
通常,只要另一個對象擁有對它的引用或方法的作用域,對象就會處於活動狀態。有時你只需要通過將物品放在財產或伊娃裏來強制它。不要擔心開銷。代碼然後在優化之前測量。 UI框架一直都會產生大量的對象。 – uchuugaka