ios arc与变量的作用域

@开启ARC编程时要注意的

      在ARC情况下,局部变量离开作用域就被销毁了,所以有些时候要注意,比如UIWebView,设成局部变量,在离开了作用域就被销毁了,但它可能还要执行delegate方法,所以程序就会崩溃。又例如,AVAudioPlayer设置成局部变量时播放不了声音,因为当离开作用域后变量就被销毁了。

- (void)viewDidLoad
{
    [super viewDidLoad];
    SecondViewController *svc = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil];
    svc.delegate = self;
    [self.view addSubview:svc.view];
}
这个SecondViewController的视图能够显示,但是点击视图上的按钮就会报错。

如果将SecondViewController的一个对象声明为ViewController的一个成员变量就正常。

不知道使用alloc的局部变量,该怎么处理呢。我在SecondViewController *svc = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil];的前面加_strong之类的关键字,不能识别...

 

理解:svc这个指针本身是在栈里分配的出了}就挂了,然后它指向的SecondViewController在堆上生成的对象随后会被析构掉。
至于视图能够正常显示应该是[self.view addSubview:svc.view]之后self.view中有强引用的指针指向svc.view  所以视图不会挂

[super dealloc];在arc中不能用了。类如果注册了通知(观察者模式),需要remove掉。这个不管是否支持arc,都必须要做的。

- (void)dealloc {

[[NSNotificationCenterdefaultCenter]removeObserver:self];//如果注册了通知的话。

[self removeObserver:self forKeyPath:keyPath];//如果注册了kvo的话。

#if !__has_feature(objc_arc)  //在这里也需要判断是否支持arc,支持的话就执行旧工程中该release的语句.
    [array release]; //array代表alloc但没有autorelease的变量
    [super dealloc];
#endif
}

posted @ 2013-11-15 11:44  天下.无贼  阅读(414)  评论(0)    收藏  举报