ios - 为什么在 dealloc 方法中没有释放对象?

标签 ios objective-c memory-management memory-leaks dealloc

我在理解 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。

  1. 既然调用了dealloc方法,所有弱指针都应该被niled

  2. 由于强指针仅在 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/

相关文章:

iphone - 带有 UINavigationController 的 UITabBarController

objective-c - 无法构建 Objective-C 模块 'ContactsUI'

c++ - 在 (operator new(unsigned int)+22) 处崩溃

C++ 使用 . 和 . 之间有什么区别?或 -> 对于链表

ios - 如何在用户退出 iPhone 应用程序时执行最后的操作?

iphone - iOS - 如何将 html 资源文件的全部内容读入 NSString *?

iphone - 更改任何单元格名称时顶部单元格名称也会更改

c++ - 有效地使用多个分配器

ios - 如何从IOS中的多个数组中搜索UITableView中的单元格

jquery - 使用 ajax 时,在 iOS 中按住文本不会在 jQueryMobile 对话框中显示 'copy' 按钮