TA的每日心情 | 汗 2024-10-15 10:05 |
---|
签到天数: 372 天 [LV.9]以坛为家II
|
本帖最后由 Sian 于 2014-1-12 13:23 编辑
本讲的主要内容是想说明一个问题:NSMutableArray在进行addObject操作时会将该对象进行一次retain操作,事实上OC的其他数据结构或自带的方法与属性同样具体该特性; 以下是程序实现:
Dog.h- //
- // Dog.h
- // Memory_myArray
- //
- // Created by yusian on 14-1-12.
- // Copyright (c) 2014年 yusian. All rights reserved.
- //
- #import <Foundation/Foundation.h>
- @interface Dog : NSObject
- {
- int _ID;
- }
- @property int ID;
- @end
复制代码 Dog.m- //
- // Dog.m
- // Memory_myArray
- //
- // Created by yusian on 14-1-12.
- // Copyright (c) 2014年 yusian. All rights reserved.
- //
- #import "Dog.h"
- @implementation Dog
- @synthesize ID = _ID;
- - (void) dealloc{
- NSLog(@"dog %d is dealloc",_ID);
- [super dealloc];
- }
- @end
复制代码 main.m- //
- // main.m
- // Memory_myArray
- //
- // Created by yusian on 14-1-12.
- // Copyright (c) 2014年 yusian. All rights reserved.
- //
- #import <Foundation/Foundation.h>
- #import "Dog.h"
- int main(int argc, const char * argv[])
- {
- @autoreleasepool {
-
-
- NSMutableArray * array = [[NSMutableArray alloc] init];
-
- for (int i = 0 ; i < 3 ; i ++)
- {
- Dog * dog = [[Dog alloc] init];
- [dog setID:i];
- NSLog(@"%ld",[dog retainCount]);
- [array addObject:dog];//Array在进行addObject操作时自动将对象的retainCount加1
- NSLog(@"%ld",[dog retainCount]);
- [dog release];
- }
- for (Dog * d in array)
- {
- NSLog(@"dog %d is in array",[d ID]);
- }
-
- [array release]; //数组进行release操作会自动将数组中引用的对象进行releae,从而dog会因再次releae而dealloc
- }
- return 0;
- }
复制代码 输出结果:- 2014-01-12 12:15:37.609 Memory_myArray[2061:303] 1
- 2014-01-12 12:15:37.610 Memory_myArray[2061:303] 2
- 2014-01-12 12:15:37.611 Memory_myArray[2061:303] 1
- 2014-01-12 12:15:37.611 Memory_myArray[2061:303] 2
- 2014-01-12 12:15:37.611 Memory_myArray[2061:303] 1
- 2014-01-12 12:15:37.612 Memory_myArray[2061:303] 2
- 2014-01-12 12:15:37.612 Memory_myArray[2061:303] dog 0 is in array
- 2014-01-12 12:15:37.612 Memory_myArray[2061:303] dog 1 is in array
- 2014-01-12 12:15:37.613 Memory_myArray[2061:303] dog 2 is in array
- 2014-01-12 12:15:37.612 Memory_myArray[2061:303] dog 0 is dealloc
- 2014-01-12 12:15:37.612 Memory_myArray[2061:303] dog 1 is dealloc
- 2014-01-12 12:15:37.612 Memory_myArray[2061:303] dog 2 is dealloc
复制代码 |
|