关于ios6中的release

wangyangkobe 2013-10-09 09:56:23
我在读这篇文章:
https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmPractical.html#//apple_ref/doc/uid/TP40004447-1000810

里面有这么一段话:
引用
Collections Own the Objects They Contain

When you add an object to a collection (such as an array, dictionary, or set), the collection takes ownership of it. The collection will relinquish ownership when the object is removed from the collection or when the collection is itself released. Thus, for example, if you want to create an array of numbers you might do either of the following:

NSMutableArray *array = <#Get a mutable array#>;
NSUInteger i;
// ...
for (i = 0; i < 10; i++) {
NSNumber *convenienceNumber = [NSNumber numberWithInteger:i];
[array addObject:convenienceNumber];
}
In this case, you didn’t invoke alloc, so there’s no need to call release. There is no need to retain the new numbers (convenienceNumber), since the array will do so.

NSMutableArray *array = <#Get a mutable array#>;
NSUInteger i;
// ...
for (i = 0; i < 10; i++) {
NSNumber *allocedNumber = [[NSNumber alloc] initWithInteger:i];
[array addObject:allocedNumber];
[allocedNumber release];
}
In this case, you do need to send allocedNumber a release message within the scope of the for loop to balance the alloc. Since the array retained the number when it was added by addObject:, it will not be deallocated while it’s in the array.

To understand this, put yourself in the position of the person who implemented the collection class. You want to make sure that no objects you’re given to look after disappear out from under you, so you send them a retain message as they’re passed in. If they’re removed, you have to send a balancing release message, and any remaining objects should be sent a release message during your own dealloc method.


但是我自己在IOS6中写个小程序,
NSMutableArray *array = [NSMutableArray array]

for (i = 0; i < 10; i++) {
NSNumber *allocedNumber = [[NSNumber alloc] initWithInteger:i];
[array addObject:allocedNumber];
}


根本不需要调用
autorelease
或者
release
,求详解。
...全文
211 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
ArcRain 2013-10-10
  • 打赏
  • 举报
回复
引用 4 楼 wangyangkobe 的回复:
好的,谢谢,那你有没什么使用心得?
ARC没用过,习惯了手动控制。之前看同事查ARC工程的内存问题,废了很大劲。
wangyangkobe 2013-10-10
  • 打赏
  • 举报
回复
引用 3 楼 dream238 的回复:
[quote=引用 2 楼 wangyangkobe 的回复:] 是不是在ios6中,如果使用ARC,程序猿就根本不需要考虑内存管理的事情。
是的,但是如果ARC使用的不好,出现内存方面的问题,查起来会比较麻烦...[/quote] 好的,谢谢,那你有没什么使用心得?
ArcRain 2013-10-10
  • 打赏
  • 举报
回复
引用 2 楼 wangyangkobe 的回复:
是不是在ios6中,如果使用ARC,程序猿就根本不需要考虑内存管理的事情。
是的,但是如果ARC使用的不好,出现内存方面的问题,查起来会比较麻烦...
wangyangkobe 2013-10-10
  • 打赏
  • 举报
回复
引用 1 楼 dream238 的回复:
你的工程是ARC的吧?ARC的话不需要调用。
是不是在ios6中,如果使用ARC,程序猿就根本不需要考虑内存管理的事情。
ArcRain 2013-10-09
  • 打赏
  • 举报
回复
你的工程是ARC的吧?ARC的话不需要调用。

29,028

社区成员

发帖
与我相关
我的任务
社区描述
主要讨论与iOS相关的软件和技术
社区管理员
  • iOS
  • 大熊猫侯佩
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧