• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Objective-C中的Strong、Copy与MutableCopy

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

面试过程中经常被问到ARC中Strong、Copy的区别是什么。普通的回答是:一样。文艺(正确)的回答是:分情况(我擦!WQY#$&Y**%OWEUR)

可以先参考这篇文章http://www.cnblogs.com/lihaiyin/p/4647426.html

 

问题一:到底用Copy还是Strong

1. 把不可变对象写成Copy:   如果把不可变对象赋值给此属性,内存中其实就是retain了一下。 如果把可变对象赋值给此属性,会生成新的不可变对象,避免值的变化

2. 把不可变对象写成Strong: 如果把不可变对象赋值给此属性,内存中其实就是retain了一下。 如果把可变对象赋值给此属性,会导致赋值后的内容依然可变

3. 把可变对象写成Strong:   如果把不可变对象赋值给此属性,调用此对象的addXX等增、删的方法时会崩溃。如果把可变对象赋值给此属性,内存中其实就是retain了一下。

4. 把可变对象写成Copy:     无论是谁赋值给此属性,都会调用Copy生成不可变对象,都会在调用此对象的addXX等增、删的方法时会崩溃

 

因此,我们的代码中一般都会  把不可变对象写成Copy  把可变对象写成Strong

 

问题二:源码中的Copy方法为什么copyItem的参数是YES?

/**
 * Returns a new copy of the receiver.<br />
 * The default abstract implementation of a copy is to use the
 * -initWithArray:copyItems: method with the flag set to YES.<br />
 * Immutable subclasses generally simply retain and return the receiver.
 */
- (id) copyWithZone: (NSZone*)zone
{
  NSArray    *copy = [NSArrayClass allocWithZone: zone];

  return [copy initWithArray: self copyItems: YES];
}

/**
 * Returns an NSMutableArray instance containing the same objects as
 * the receiver.<br />
 * The default implementation does this by calling the
 * -initWithArray:copyItems: method on a newly created object,
 * and passing it NO to tell it just to retain the items.
 */
- (id) mutableCopyWithZone: (NSZone*)zone
{
  NSMutableArray    *copy = [NSMutableArrayClass allocWithZone: zone];

  return [copy initWithArray: self copyItems: NO];
}

对比一下,发现initWithArray:copyItems方法的参数很怪。都知道,无论NSArray是copy还是mutableCopy,item都是retain的,不会copy,那为啥copyWithZone方法(copy方法调用时会调用此方法)的实现中,copyItem的参数是YES?

-initWithArray:copyItems: method with the flag set to YES.<br />
 * Immutable subclasses generally simply retain and return the receiver

想了很久,后来发现,答案就在注释中,不可变子类(NSString、NSArray、NSDictionary)一般只是简单的retain。。。对不可变对象调用copy只是retain,对可变对象调用copy会生成不可变对象,所以,为了使得新生成的NSArray“不可变”(元素本身也要不可变),只能使用copy,但这里的copy并非为item生成了新的对象,只是为了生成“不可变”的对象

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Objective-C#pragma mark发布时间:2022-07-12
下一篇:
Objective-C创建目录接口createDirectoryAtPath:withIntermediateDirectories:attribu ...发布时间:2022-07-12
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap