加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

objective-c – 为什么要使用类方法构造函数而不是alloc / init

发布时间:2020-12-16 03:26:10 所属栏目:百科 来源:网络整理
导读:Objective C / Cocoa中的构造函数有两种选择: 1.类构造函数 Product *product = [Product productWithIdentifier:@"Chocolate"];// Use product 2. Alloc / init构造函数 Product *product = [[Product alloc] initWithIdentifier:@"Chocolate"];// Use pro
Objective C / Cocoa中的构造函数有两种选择:

1.类构造函数

Product *product = [Product productWithIdentifier:@"Chocolate"];
// Use product

2. Alloc / init构造函数

Product *product = [[Product alloc] initWithIdentifier:@"Chocolate"];
// Use product
[product release];

我所做的

>我倾向于使用类方法只是因为它看起来更干净而且你不需要发布.
>我看到很多alloc / init – 这样做有什么好处?

我的问题

>哪一个更好?或者只是品味问题?

对于上下文,Product类将具有以下内容:

+(Product *)productWithIdentifier:(NSString *)identifier_ {
   return [[[[self class] alloc] initWithIdentifier:identifier] autorelease];
}

-(Product *)initWithIndentifier:(NSString *)identifier_ {
   self = [super init]
   if (self) {
       identifier = identifier_;
   }
   return self;
}

解决方法

如果您使用ARC,那么两者之间并没有那么大的区别.如果您不使用ARC,差异非常重要.

alloc / init组合为您提供了拥有引用.这意味着你必须在以后发布它. classnameWithFoo变量返回非拥有引用.你可能不会发布它.

这遵循通常的Cocoa命名约定.除了以alloc,copy,mutableCopy和new开头的方法之外,所有方法都返回非拥有(自动释放)实例.这些返回您必须释放的拥有引用.

使用哪一个主要是品味问题.但是,如果您需要可以快速处理的临时对象,则alloc变量会导致稍微减少的方法调用(自动释放),并且在循环中,它还会减少最大内存占用量.但是,在大多数情况下,这种降低的成本是可以忽略的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读