OC学习笔记(3)类的初始化与存取器方法

来源:互联网 发布:高级ios程序员招聘 编辑:程序博客网 时间:2024/05/22 15:18

1、ASRectangle.h

#import <Foundation/Foundation.h>@interface ASRectangle : NSObject{@public    double width;    double height;}-(void) setWidth1:(double)aWidth height:(double)aHeight;-(double) area;-(double) len;//指定初始化-(id) initWithWH:(double)aWidth height:(double)aHeight;-(double) width;-(double) height;//存取器方法-(void) setWidth:(double)aWidth;-(void) setHeight:(double)aHeight;@end

2、ASRectangle.m

#import "ASRectangle.h"@implementation ASRectangle-(void) setWidth1:(double)aWidth height:(double)aHeight{    width = aWidth;    height = aHeight;}-(double) area{    return width * height;}-(double) len{    return 2*(width + height);}//继承自父类的方法,可以直接在.m里定义-(id) init{    if (self = [super init]) {        height = 10;        width = 20;    }    return self;}-(double)width{    return width;}-(double)height{    return height;}-(void) setWidth:(double)aWidth{    width = aWidth;}-(void) setHeight:(double)aHeight{    height = aHeight;}@end

3、main.m

#import <Foundation/Foundation.h>#import "ASRectangle.h"int main(){    @autoreleasepool {        //初始化方法        ASRectangle *rec = [[ASRectangle alloc] init];        NSLog(@"%f  %f",[rec area],[rec len]);        NSLog(@"%f  %f",rec->width,rec->height);                //设置        [rec setWidth1:3 height:4];        NSLog(@"%f  %f",[rec area],[rec len]);        NSLog(@"%f  %f",rec->width,rec->height);                //取变量方法        rec->width = 10;        rec->height = 11;        NSLog(@"%f  %f",[rec area],[rec len]);        NSLog(@"%f  %f",rec->width,rec->height);                //存取器方法        rec.width = 15;        rec.height = 16;        NSLog(@"%f  %f",[rec area],[rec len]);        NSLog(@"%f  %f",rec->width,rec->height);        [rec release];    }}//初始化方法的实现//自定义初始化方法首先需要调用父类的初始化方法,初始化继承的父类的数据成员。//如果父类的初始化方法执行失败,则直接返回nil,确认父类初始化函数执行成功后,初始化本类新增的实例变量//最后返回self给方法的调用者//self是方法的隐藏函数,代表对象本身//OC的初始化方法可以有多个,一般所有的初始化方法都以init开头//初始化方法定义成实例方法//参数少得初始化函数调用指定初始化方法,完成类的初始化//指定初始化方法:是可以初始化每一个实例变量的方法//必须调用父类的指定初始化方法//应该将self作为初始化的返回值//应该直接通过实例变量进行赋值操作//存取器方法//得到实例变量值的方法成为getter方法,一般和实例变量同名//设置实例变量值的方法成为setter,setter方法命名格式为:setPropertyName(首字母大写)




0 0
原创粉丝点击