• Objective-C:ARC自动释放对象内存


    ARC是cocoa系统帮你完成对象内存释放的引用计数机制

        .h文件

     1 //  Person.h
     2 //  01-ARC
     3 //
     4 //  Created by ma c on 15/8/13.
     5 //  Copyright (c) 2015年. All rights reserved.
     6 //
     7 
     8 #import <Foundation/Foundation.h>
     9 
    10 @interface Person : NSObject
    11 @property(nonatomic,strong)NSString *name;
    12 @property(nonatomic,assign)NSInteger age;
    13 +(Person*)personWithName:(NSString*) name andAge:(NSInteger) age;
    14 -(id)initWithName:(NSString*) name andAge:(NSInteger) age;
    15 -(void)show;
    16 @end

        .m文件

     1 //  Person.m
     2 //  01-ARC
     3 //
     4 //  Created by ma c on 15/8/13.
     5 //  Copyright (c) 2015年. All rights reserved.
     6 //
     7 
     8 #import "Person.h"
     9 
    10 @implementation Person
    11 -(id)initWithName:(NSString*) name andAge:(NSInteger) age
    12 {
    13     self = [super init];
    14     if(self)
    15     {
    16         _name = name;
    17         _age = age;
    18     }
    19     return self;
    20 }
    21 
    22 /*
    23  在类方法中,由于没有创建对象实例,所以:self指针不能用,实例变量不能用。
    24  */
    25 +(Person*)personWithName:(NSString*) name andAge:(NSInteger) age
    26 {
    27     return [[Person alloc]initWithName:name andAge:age];
    28 }
    29 
    30 -(void)show
    31 {
    32     NSLog(@"name:%@,age:%ld",_name,_age);
    33 }
    34 
    35 /*
    36 创建对象时是先创建父类的部分,再创建子类的部分;
    37  销毁对象时,顺序正好相反
    38  ARC禁止显式的发送dealloc消息
    39 */
    40 -(void)dealloc
    41 {
    42     NSLog(@"person dealloc");
    43     //[super dealloc]; //禁止显式的发送dealloc消息
    44 }
    45 @end

        主函数测试

     1 //  main.m
     2 //  01-ARC
     3 //
     4 //  Created by ma c on 15/8/13.
     5 //  Copyright (c) 2015年. All rights reserved.
     6 //
     7 
     8 #import <Foundation/Foundation.h>
     9 #import "Person.h"
    10 int main(int argc, const char * argv[])
    11 {
    12     @autoreleasepool
    13     {
    14         Person *person = [[Person alloc]initWithName:@"Jim" andAge:22];
    15         
    16         [person show];
    17         //[person dealloc];//error,底层会自动调用该方法用来销毁对象
    18     }
    19     return 0;
    20 }

        测试结果:

    2015-08-13 17:48:54.904 01-ARC[1636:107161] name:Jim,age:22
    2015-08-13 17:48:54.905 01-ARC[1636:107161] person dealloc
    Program ended with exit code: 0
  • 相关阅读:
    Android_bug之 task ':app:mergeDebugResources'. > Some file crunching failed, see logs f
    linux下vi命令大全[转]
    百度地图api 常用demo
    Mac之vim普通命令使用[转]
    java写文件
    java读取文件
    Android中对Log日志文件的分析[转]
    Android实用代码模块集锦
    java 位运算
    MyEclipse自带maven找不到或自己外置安装
  • 原文地址:https://www.cnblogs.com/XYQ-208910/p/4728052.html
Copyright © 2020-2023  润新知