OC类的使用,属性声明与复合类的实现示例

OC类的使用,属性声明与复合类的实现示例

/*********XYPoint.h***********/

#import <Foundation/Foundation.h>

 

@interface XYPoint : NSObject{

    int x;

    int y;

}

@property(nonatomic,assign)int x;

@property(nonatomic,assign)int y;

 

-(id)initWithX: (int)_x andY: (int)_y;

 

-(NSString*)description;

@end

 

/*********XYPoint.m**********/

 

#import "XYPoint.h"

 

@implementation XYPoint

@synthesize x,y;

 

-(id)initWithX: (int)_x andY: (int)_y

{

    if (self = [super init]) {

        x = _x;

        y = _y;

    }

    return self;

}

 

-(NSString*)description

{

    return [NSString stringWithFormat: @"(%d,%d)",x,y];

}

 

@end

 

 

/*********Circle.h*********/

#import <Foundation/Foundation.h>

#import "XYPoint.h"

//复合类: 一个类的成员变量为另外一个类的对象

@interface Circle : NSObject{

    int radius;

    XYPoint* origin;//圆心

}

//赋值方式:assign  retain copy 其中assign适用于简单类型的数据

@property(nonatomic,assign)int radius;

@property(nonatomic,retain)XYPoint* origin;

-(id)initWithRadius: (int)_r andOrigin: (XYPoint*)_p;

-(NSString*)description;

 

-(void)dealloc;//类似于C++中的析构函数

@end

 

/**********Circle.m************/

 

#import "Circle.h"

 

@implementation Circle

@synthesize radius,origin;

//将对Circle类的相关总结放入帖子中

 

-(id)initWithRadius: (int)_r andOrigin: (XYPoint*)_p

{//基类部分成员的初始化[super init];

    if (self = [super init]) {

        //本类特有实例变量的初始化

        radius = _r;

        //origin = _p;

        origin = [[XYPoint alloc] initWithX:_p.x andY:_p.y];

    }

    return self;

}

//重写基类的dealloc方法   如果类中有指向堆空间的实例变量,为了避免出现内存泄漏,则需要重写dealloc方法

//方法重写:在派生类中定义一个与基类原型相同的方法,则派生类中重写了基类的方法。

-(void)dealloc

{

    [origin release];

    [super dealloc];//回收基类部分成员的资源

}

-(NSString*)description

{

    return [NSString stringWithFormat: @"radius:%d,origin:%@",radius,origin];

}

@end

 

 

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

#import <Foundation/Foundation.h>

#import "XYPoint.h"

#import "Circle.h"

 

int main(int argc, const char * argv[])

{

    

    @autoreleasepool {

//消息机制:[receiver message];如果receiver是类对象,则与message同名的方法需要为类方法(+)(注:类方法相当于c++中的静态成员函数),如果receiver是实例化对象,则与message同名的方法需要为实例方法(-)。

        XYPoint* p = [[XYPoint alloc] initWithX:1 andY:1];//声明并初始化对象

        //对象本质就是指针。

        //alloc:申请堆空间 如果申请堆空间成功,则返回OC实例化对象(即返回堆空间的首地址)。

    

        p.x = 10;//对象名.属性名做左值,等价于[p setX:10];

        NSLog(@"%d",p.x);//对象名.属性名做右值或者读取,等价于[p x];

        NSLog(@"%@",p);

        

        Circle* c = [[Circle alloc] initWithRadius:10 andOrigin:p];//思考:初始化c时的内存分析图是怎样的?

        NSLog(@"c:%@",c);

        [p release];

        [c release];

    }

    return 0;

}

 

 

原文地址:https://www.cnblogs.com/about-zj-blog/p/5292565.html