一、OC中的类有两个文件组成,一个.h声明文件和一个.m实现文件;
Student.h文件
//@interface 声明要定义一个类,以@end表示结束
//Student 我们要定义的类名
//: 代表继承
//NSObject 代表Student所继承的父类
@interface Student : NSObject {
//成员变量,需要定义在{}的范围里面
@public
@protected
@private
int _age;
}
//成员函数,在这里声明的所有方法都是公共方法
// - 代表动态方法,+ 代表静态方法
- (int)getAge; //开头的括号为返回值类型
- (void)setAge : (int)age; //冒号代表一个参数位置,一个冒号对应一个参数;参数的类型需要用括号,紧接着是参数名;
@end
Student.m文件
#import "Student.h"
@implementation Student
- (int)getAge {
return _age;
}
- (void)setAge:(int)age {
_age = age;
}
@end
获得Student类的对象并且使用:
#import <Foundation/Foundation.h>
#import "Student.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
//[Student alloc] 在内存中为Student的对象开辟一块内存
//通过init 方法来进行对这个对象的初始化
Student *student = [[Student alloc] init];
//调用student对象的方法,OC中对象方法的调用需要在[]里面进行,左边是对象明,右边是方法名,参数由:好分开;
[student setAge:20];
int age = [student age];
// insert code here...
NSLog(@"Student age = %i", age);
}
return 0;
}
二、创建一个带参数的初始化方法
.h文件中声明:
//带参数的初始化方法
- (id)initWithAge:(int)age;
-(id)initWithAge:(int)age {
if (self = [super init]) {
_age = age;
}
return self;
}
使用这个方法来获得对象:
Student *student = [[Student alloc] initWithAge:5];
NSLog(@"Student age = %i", student.age);