码迷,mamicode.com
首页 > 其他好文 > 详细

属性声明和实现

时间:2015-12-10 13:31:28      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:


//
//  Person.h
//  属性的声明和实现
//
//  Created by MAC on 15/12/10.
//  Copyright © 2015年 MAC. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface Person : NSObject
{
    @private
    int _pid;
    NSString *_name;
    int _age;
}
-(void)setPid:(int)pid;
-(void)setName:(NSString*)name;
-(void)setAge:(int)age;

-(int)pid;
-(NSString*)name;
-(int)age;
@end

 

 
//
//  Person.m
//  属性的声明和实现
//
//  Created by MAC on 15/12/10.
//  Copyright © 2015年 MAC. All rights reserved.
//

#import "Person.h"

@implementation Person
-(void)setPid:(int)pid{
    self->_pid = pid;
}
-(void)setName:(NSString*)name{
    self->_name = name;
}
-(void)setAge:(int)age{
    self->_age = age;
}
-(int)pid{
    return _pid;
}
-(NSString*)name{
    return _name;
}
-(int)age{
    return _age;
}
@end

//
//  main.m
//  属性的声明和实现
//
//  Created by MAC on 15/12/10.
//  Copyright © 2015年 MAC. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "Person.h"
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Person *person = [[Person alloc]init];
        [person setPid:444];
        [person setName:@"xiaoren"];
        [person setAge:20];
        NSLog(@"%d %@ %d",person.pid,person.name,person.age);  //没有参数的方法可以直接用点语法
    }
    return 0;
}

 

      可以用@property简化方法  
//
//  Person.h
//  属性的声明和实现
//
//  Created by MAC on 15/12/10.
//  Copyright © 2015年 MAC. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface Person : NSObject
{
    @private
    int _pid;
    NSString *_name;
    int _age;
}

@property int pid;
@property NSString *name;
@property int age;

@end

//
//  main.m
//  属性的声明和实现
//
//  Created by MAC on 15/12/10.
//  Copyright © 2015年 MAC. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "Person.h"
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Person *person = [[Person alloc]init];
        [person setPid:33];
        [person setName:@"renren"];
        [person setAge:20];
        int pid = [person pid];
        NSString *name = [person name];
        int  age = [person age];
        NSLog(@"%d %@ %d",pid,name,age);

    }
    return 0;
}

 

 

 

属性声明和实现

标签:

原文地址:http://www.cnblogs.com/WJR12/p/5035599.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!