重构Oc的get,set方法

重构Point2类

本案例使用四种属性定义方式(本质->声明式->IOS5.0->IOS6.0)重构Point2类,类中有横坐标x、纵坐标y两个属性,并且有一个能显示位置show方法。在主程序中创建两个Point2类的对象,设置其横纵坐标,并将它们显示出来。


Point2.h

//
//  Point2.h
//  Oc-Day1
//
//  Created by spare on 16/4/9.
//  Copyright © 2016年 spare. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface Point2 : NSObject
{
//    int x;
//    int y;
    //与声明式方式的区别尽在于此,此处不需要再声明实例变量了。
}
//-(void)setX:(int)x1;
//-(int)getx;
//-(void)setY:(int)y1;
//-(int)getY;
//直接使用@property定义实例变量和生成实例变量setter函数和getter函数的声明。
@property int x,y;
-(void)show;
@end



Point2.m

//
//  Point2.m
//  Oc-Day1
//
//  Created by spare on 16/4/9.
//  Copyright © 2016年 spare. All rights reserved.
//

#import "Point2.h"

@implementation Point2

//-(void)setX:(int)x1{
//    x=x1;
//}
//-(int)getx{
//    return x;
//}
//-(void)setY:(int)y1{
//    y=y1;
//}
//-(int)getY{
//    return y;
//}
//与iOS5.0方式不同,此处不需要再声明属性的实现了,即@synthesize部分。
@synthesize x,y;

-(void)show{
    NSLog(@"x=%d,y=%d",x,y);
}

@end

main.m

//
//  main.m
//  Oc-Day1
//
//  Created by spare on 16/4/9.
//  Copyright © 2016年 spare. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "Student.h"
#import "Point2.h"


int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
//        Student *stu=[[Student alloc]init];
//        [stu setAge:15];
//        [stu setSalary:10000];
//        [stu setGender:'M'];
//        
//        [stu printInfo];
        
        Point2 *p = [[Point2 alloc] init];
//        [p setX:10];
//        [p setY:20];
        p.x=10;//使用属性的点运算符为属性赋值。
        p.y=20;
        [p show];
        Point2 *p1 = [[Point2 alloc] init];
//        [p1 setX:55];
//        [p1 setY:77];
        p1.x=55;
        p1.y=77;
        [p1 show];
  
        
    }
    return 0;
}



你可能感兴趣的:(重构Oc的get,set方法)