当没有dealloc方法时,我应该自动释放保留的属性/实例变量吗?

Geo*_*rge 0 memory-management objective-c

我正在学习内存管理一段时间.阅读Apple的内存管理指南以及其他作者的书籍/博客/论文/帖子.

令我困惑的是我是否应该写:

nameOfMySynthesizedProperty = [[NSObject alloc] init]; // version 1
Run Code Online (Sandbox Code Playgroud)

要么

nameOfMySynthesizedProperty = [[[NSObject alloc] init] autorelease]; // version 2
Run Code Online (Sandbox Code Playgroud)

在示例项目中,使用手动内存管理,没有dealloc方法,版本1用于所有类属性/ ivars.有时一些属性甚至没有合成但是它的吸气剂被使用,

这些都没有在我读过的教程/指南中讲授,但是这个示例项目顺利进行而没有崩溃......

任何人都可以给我一些亮点......

更新1

示例项目中使用手动内存管理.

更新2

另一个例子

AppDelegate.h

#import <UIKit/UIKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate>
{
}
@property (nonatomic, retain) UIWindow *window;
@property (nonatomic, retain) UIViewController *viewController;
@end
Run Code Online (Sandbox Code Playgroud)

AppDelegate.m

@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // To be inserted with the following choices of code
}
@end
Run Code Online (Sandbox Code Playgroud)

AppDelegate.m- > -(BOOL)application:application didFinishLaunchingWithOptions:方法中,以下哪个对于初始化是正确的self.window.rootViewController?(使用手动内存管理.使用Xcode 5.)

版本1

self.window.rootViewController = [[UIViewController alloc] init];
self.viewController = [[[UIViewControllerDrawer alloc]init] autorelease];
self.window.rootViewController = self.viewController;
Run Code Online (Sandbox Code Playgroud)

版本2

self.window.rootViewController = [[[UIViewController alloc] init] autorelease];
self.viewController = [[[UIViewControllerDrawer alloc]init] autorelease];
self.window.rootViewController = self.viewController;
Run Code Online (Sandbox Code Playgroud)

版本3

self.viewController = [[[UIViewControllerDrawer alloc]init] autorelease];
self.window.rootViewController = self.viewController;
Run Code Online (Sandbox Code Playgroud)

我知道这window是一个属性(它的实例变量也被命名为window).但是是window.rootViewController一个实例变量吗?实验结果显示版本3正在运行,版本1和版本2崩溃.

Rob*_*ier 6

都不是.你应该使用ARC.今天很少有理由使用手动内存管理.(理解 ARC如何应用内存管理规则很有用,但直接使用它是个坏主意.)

如果您绝对必须使用手动内存管理,那么您通常也不应该通过这种方式直接访问ivars.除了init和之外dealloc,你应该这样做:

self.property = [[[NSObject alloc] init] autorelease];
Run Code Online (Sandbox Code Playgroud)

init,你应该这样做:

_property = [[NSObject alloc] init];
Run Code Online (Sandbox Code Playgroud)

在任何一种情况下(但只有在您使用手动内存管理时,您不应该这样做),您将需要以下内容dealloc:

[_property release];
_property = nil;
Run Code Online (Sandbox Code Playgroud)

精确规则的最佳参考是内存管理策略.

但我不能强调:如果你甚至问这些问题,你应该使用ARC.如果您不必问这些问题,您应该已经知道为什么要使用ARC.如果您遇到某种非常专业的问题(例如在32位OS X上运行),那么您可能已经知道规则以及如何正确应用它们.

如果您遇到手动内存管理的现有代码,您应该使用"编辑>重构>转换为Objective-C ARC ..."来为您修复它.