OC-内存管理1.1

来源:互联网 发布:postgresql 海量数据 编辑:程序博客网 时间:2024/06/18 09:57

/*****************person.h*****************/

/*

程序设计目的:

类具有和C语言结构体相似的特征,每个类创建的对象都会拷贝本类的成员方法(函数又称消息)和成员变量(又称字段)放在自己的内存空间中,以后对象再次调用函数或乘员变量时实际上是调用自己内存中的拷贝,而本例题就是为了证明这一点而专门设计的。

注:实验前请关闭ARC

*/

#import <Foundation/Foundation.h>

@class Dog;

@interface Person :NSObject

{

   Dog *_dog;

   NSString *_name;

   NSInteger _age;

}

-(id)initWithName:(NSString *)newName andAge:(NSInteger)newAge;

-(void)showme;

@property(nonatomic,readonly)NSString *name;

-(NSInteger)age;

@property(copy) Dog *dog;

-(void)setDog:(Dog *)dog;

@end

/*****************person.m*****************/

#import "Person.h"

#import "Dog.h"

@implementation Person


-(id)initWithName:(NSString *)newName andAge:(NSInteger)newAge{

   _name = newName;

   _age = newAge;

    return self;

}

-(void)showme{

    NSLog(@"I'm %@ age:%li",self.name,(long)self.age);

}

-(NSInteger)age{return _age;}

@synthesize dog = _dog;

//方法的实现展开:

-(void)setDog:(Dog *)dog{

   if (dog!=_dog) {

        //_dog可能为空,OC允许[_dog release];

        [_dogrelease];

       _dog = [dogretain];

    }

}

@end

/*****************Dog.h*****************/

#import <Foundation/Foundation.h>


@interface Dog : NSObject

{

   int _ID;


}

@property int ID;

-(void)print_counter;

-(void)bug;

@end

/*****************Dog.m*****************/

#import "Dog.h"


@implementation Dog

//打印目前dog的引用计数(reference counting)的值

-(void)print_counter{NSLog(@"retaincount:%li",[selfretainCount]);}

//狗叫:

-(void)bug{NSLog(@"T'm a dog!");}

@end

/*****************main.m*****************/

#import <Foundation/Foundation.h>

#import "Person.h"

#import "Dog.h"

int main(int argc,constchar * argv[])

{

    @autoreleasepool {


        Person *No_1 = [[Person alloc] initWithName:@"Tom" andAge:18];

        Person *No_2 = [[Personalloc]initWithName:@"Bieber"andAge:21];

        

       Dog *dog_1 = [[Dogalloc]init];

       Dog *dog_2 = [[Dogalloc]init];

       Dog *dog_3 = [[Dogalloc]init];

       //测试:

        [No_1setDog:dog_1];

        [dog_1print_counter];

        

        [No_2setDog:dog_2];

        [dog_2print_counter];

        

        [No_1setDog:dog_3];

        [dog_1print_counter];

        

        [No_1showme];

        [No_2showme];

       /*

         输出信息:

         2014-11-16 14:57:48.760 Ram_control[1092:303] retaincount:2

         2014-11-16 14:57:48.761 Ram_control[1092:303] retaincount:2

         2014-11-16 14:57:48.762 Ram_control[1092:303] retaincount:1

         2014-11-16 14:57:48.762 Ram_control[1092:303] I'm Tom age:18

         2014-11-16 14:57:48.763 Ram_control[1092:303] I'm Bieber age:21

         */

        //测试结果,一个类的对象会把类里面的成员方法和变量都单独的拷贝一份在自己的内存空间里,(static或全局变量另行讨论)每个对象每次调用的类的成员函数或者成员变量实际上都是自己拷贝的那一份。类似于C语言中的结构体。

    }

   return 0;

}

0 0
原创粉丝点击