创建一个类,由.h文件声明部分和.m文件实现部分组成,一个类通常继承自NSObject,.h文件内容如下所示:
#import <Foundation/Foundation.h>
@interface Person : NSObject {
// 声明成员变量,可以使用的访问修饰符有public,private,protected
// 使用时需要在访问修饰符前添加@,如@public
@public
NSString *name;
int age;
float height;
}
// 声明方法
// - 开头的为成员方法,+开头的为类方法
//凡是以init开头的方法通常为构造方法
- (id)init;
- (id)initWithAge: (int)newAge;
- (id)initWithAge: (int)newAge andHeight: (float)newHeight;
- (id)initWithAge: (int)newAge andHeight: (float)newHeight andName: (NSString *)newName;
// set方法
- (void)setName: (NSString *)name;
- (void)setAge: (int)age;
- (void)setHeight: (float)height;
// get方法
- (NSString *)getName;
- (int)getAge;
- (float)getHeight;
@end
#import "Person.h"
@implementation Person {
// 此处也可声明成员变量,不过在此处声明的成员变量仅能在类内使用
}
- (id)init {
// super init方法:1.分配空间,2.将self指向该空间
if (self = [super init]) {
name = @"zhangsan";
age = 18;
height = 170.0;
}
return self;
}
- (id)initWithAge: (int)newAge {
if (self = [super init]) {
name = @"zhangsan";
age = newAge;
height = 170.0;
}
return self;
}
- (id)initWithAge: (int)newAge andHeight: (float)newHeight {
if (self = [super init]) {
name = @"zhangsan";
age = 18;
height = newHeight;
}
return self;
}
- (id)initWithAge:(int)newAge andHeight:(float)newHeight andName:(NSString *)newName {
if (self = [super init]) {
name = newName;
age = newAge;
height = newHeight;
}
return self;
}
- (void)setName: (NSString *)aName {
self->name = aName;
}
- (void)setAge: (int)aAge {
self->age = aAge;
}
- (void)setHeight: (float)aHeight {
self->height = aHeight;
}
- (NSString *)getName {
return self->name;
}
- (int)getAge {
return self->age;
}
- (float)getHeight {
return self->height;
}
@end