4.2OC8-@property和synthesize

4.2OC8-@property和synthesize

例一:

-------------main.m-----------------

//

//  main.m

//  构造方法

//

//  Created by liuyes on 13-12-8.

//  Copyright (c) 2013年 renhe. All rights reserved.

//

 

#import <Foundation/Foundation.h>

#import "Student.h"

 

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

{

 

    @autoreleasepool {

 

        Student *stu = [[Student alloc] init];

        stu.age = 29;

        int age = stu.age;

        

        NSLog(@"age is %i", age);

        [stu release];

    }

    return 0;

}

 

-------------Student.h-----------------

 

//  Student.h

//  构造方法

//

//  Created by liuyes on 13-12-8.

//  Copyright (c) 2013年 renhe. All rights reserved.

//

 

#import <Foundation/Foundation.h>

 

@interface Student : NSObject{

    //默认是@protected

    int age;

    int no;

    float height;

    

}

 

//当编译器遇到@property时,会自动展开成getter和setter的声明

//- (void)setAge:(int)age;

//- (int)age;

@propertyint age;

 

@propertyint no;

 

@propertyfloat height;

 

@end

 

-------------Student.m-----------------

//

//  Student.m

//  Copyright (c) 2013年 renhe. All rights reserved.

//

 

#import "Student.h"

 

@implementation Student

 

@synthesize age;

@synthesize no;

@synthesize height;

 

@end

 

例二:

-------------main.m-----------------

 //

//  main.m

//  构造方法

//

//  Created by liuyes on 13-12-8.

//  Copyright (c) 2013年 renhe. All rights reserved.

//

 

#import <Foundation/Foundation.h>

#import "Student.h"

 

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

{

 

    @autoreleasepool {

 

        Student *stu = [[Student alloc] init];

        stu.age = 29;

        int age = stu.age;

        

        NSLog(@"age is %i", age);

        [stu release];

    }

    return 0;

}

 

-------------Student.h-----------------

 

 

//  Student.h

//  构造方法

//

//  Created by liuyes on 13-12-8.

//  Copyright (c) 2013年 renhe. All rights reserved.

//

 

#import <Foundation/Foundation.h>

 

@interface Student : NSObject{

    //默认是@protected

    int _age;

    int _no;

    float _height;

    

}

 

//当编译器遇到@property时,会自动展开成getter和setter的声明

//- (void)setAge:(int)age;

//- (int)age;

@propertyint age;

 

@propertyint no;

 

@propertyfloat height;

 

@end

 
 

-------------Student.m-----------------

 //

//  Student.m

//  Copyright (c) 2013年 renhe. All rights reserved.

//

 

#import "Student.h"

 

@implementation Student

 

@synthesize age = _age;

@synthesize no = _no;

@synthesize height = _height;

 

@end

 

  

例三:

-------------main.m-----------------

 

-------------Student.h-----------------

 

-------------Student.m-----------------

 

猜你喜欢

转载自javazhuang.iteye.com/blog/1986841