1、首先关闭ARC
2、手动管理内存实例 - <font size="4">#import <Foundation/Foundation.h>
- #pragma mark Person类定义部分
- @interface Person : NSObject
- @property NSString *name;
- @property int age;
- @end
- #pragma mark Person类实现部分
- @implementation Person
- //对象的临终遗言,对象销毁时,会默认调用该方法
- //【注意】该方法是系统根据引用计数器自动调用的,不需要手动调用
- -(void)dealloc{
- NSLog(@"This person dead....");
- //再释放父类
- [super dealloc];
- }
- @end
- int main(int argc, const char * argv[])
- {
- @autoreleasepool {
- //用Person类实例化一个对象
- Person *p = [Person new];//此时对象的所有者是自己
-
- //证明该对象有一个所有者
- NSInteger count = [p retainCount];
- NSLog(@"count1 = %lu",count);
-
- //引用计数器+1
- //两个指针指向一个对象,但是下面这个方法并不能是计数器+1
- Person *p2 = p;
- count = [p2 retainCount];
- NSLog(@"count2 = %lu",count);
- //只有通过retain方法可以使计数器+1
- Person *p3 = [p retain];
- count = [p retainCount];
- NSLog(@"count3 = %lu",count);
-
- //想要回收对象,则要想办法是retainCount从2变成0
- [p release];
- [p3 release];
- //想要证明person对象被释放了,可以重写其dealloc放法
- }
- return 0;
- }</font>
复制代码打印结果: 2015-10-06 10:32:56.855 MRCDemo[925:303] count1 = 1 2015-10-06 10:32:56.857 MRCDemo[925:303] count2 = 1 2015-10-06 10:32:56.857 MRCDemo[925:303] count3 = 2
2015-10-06 10:32:56.858 MRCDemo[925:303] This persondead....
|