oc类中实现属性有两种方法,一种是使用OC自定义的格式来实现类的属性,另一种是手动实现类的属性,本篇文章就是章节如何通过自定义的方式实现类的属性效果:
定义一个student类,具体的代码如下所示:
//student.h
#import <Foundation/Foundation.h>
@interface student : NSObject
{
int Age;
NSString *Name;
}
-(void)setAge:(int)_age;
-(void)setName:(NSString *)_name;
-(int)Age;
-(NSString *)Name;
@end
//student.m
#import "student.h"
#import <Foundation/Foundation.h>
@implementation student
//定义Age成员变量的读取器
//定义Name成员变量的读取器
-(void)setAge:(int)_age
{
Age = _age;
}
-(void)setName:(NSString *)_name
{
Name = _name;
}
-(int)Age
{
return Age;
}
-(NSString *)Name
{
return Name;
}
@end
调用的代码:
#import <Foundation/Foundation.h>
#import "student.h"
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
/////////////////////
student *s = [[student alloc] init];
[s setName:@"xingchen"];
[s setAge:100];
NSLog([s Name]);
/////////////////////
[pool drain];
return 0;
}
THE END !