我在理解 Objective-C 和 ARC 时遇到问题。
据我了解,强指针会自动为您解除分配,因此您不必考虑(在 dealloc 方法中解除分配,或者在上次使用对象之后解除分配?)。
所以我写了一个小应用,有 2 个 viewController 和一个 NavigationController,它进入一个 View 然后返回。
调用了 dealloc 方法,但是我在 viewDidLoad 方法中设置的属性没有被释放,它仍然指向某个对象。
代码: 第一个 viewController 有一个按钮,通过按下它,执行到另一个 viewController 的 segue。那里没有代码。
SecondViewController.m
@interface SecondViewController ()
@property (nonatomic, strong) NSString *myString;
@end
@implementation SecondViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"%@", _myString);
_myString = @"it works";
}
- (void)dealloc {
NSLog(@"%@", _myString);
// and now it is deallocating the _myString property ???
}
@end
然后,我尝试做另一件事。
我们的想法是创建一个弱指针,它指向与强指针相同的内存地址。不过,无论如何,弱指针都应该为 nil。
既然调用了dealloc方法,所有弱指针都应该被niled
由于强指针仅在 viewDidLoad 中使用,因此应在 dealloc 方法之前对其进行释放。
问题是,它没有被释放。 为什么?
secondViewController 的代码:
@interface SecondViewController ()
@property (nonatomic, strong) NSString *myString;
@property (nonatomic, weak) NSString *test;
@end
@implementation SecondViewController
- (void)viewDidLoad
{
[super viewDidLoad];
NSLog(@"%@", _myString);
_myString = @"it works";
_test = _myString;
}
- (void)dealloc
{
NSLog(@"%@", _test);
}
@end
最佳答案
属性的释放发生在 dealloc 方法的末尾。如果覆盖 dealloc 方法,属性将不会在该方法内被释放。
您可以通过在第一个 View Controller 中创建一个 weak 属性来测试它,分配第二个 View Controller 的 strong 属性,然后在应用程序返回到第一个 View Controller 时记录它的值。
关于ios - 为什么在 dealloc 方法中没有释放对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29265773/