如果我将指针设置为nil,自动引用计数是否释放对象?

DrE*_*tro 4 cocoa-touch ios automatic-ref-counting

如果我将指针设置为nil或将指针指定给另一个对象,自动引用计数是否释放对象?

例如做类似的事情:

//in .h file

@interface CustomView : UIView
{
   UIView *currentView;
}


// in .m file:

-(void)createView1
{
   currentView = [[UIView alloc] init];
   [self addSubview:currentView];
}

-(void)createView2
{
   [currentView removeFromSuperview];

   // does the former view get released by arc
   // or does this leak?
   currentView = [[UIView alloc] init];
   [self addSubview:currentView];
}
Run Code Online (Sandbox Code Playgroud)

如果此代码泄漏,我将如何正确声明*currentView?或者我如何让ARC"释放"当前视图?谢谢!

tar*_*mes 6

使用ARC,您无需考虑release/retain.

由于您的变量将被隐式定义为strong不需要将其设置为NULL- 它将在分配之前被释放.

我个人虽然喜欢声明属性:

@property (strong, nonatomic) UIView *currentView;
Run Code Online (Sandbox Code Playgroud)

  • `nil`.仅供参考 - http://stackoverflow.com/questions/557582/null-vs-nil-in-objective-c (2认同)