首先创建一个项目BMITime。
1、创建类的过程
File->New->New File...。选择OS X区域的Cocoa,选择Objective-C class模板,然后点击next按钮
将类命名为BNRPerson,并设置为NSObject的子类。最后勾选BMITime目标,点击Create按钮。
#import <Foundation/Foundation.h>
@interface BNRPerson : NSObject
{
//声明两个实例变量,一般以“_”开头
float _heightInMeters;
int _weightInKilos;
}
//声明存取方法,注意名称的书写。取方法的名字是去掉实例变量的下划线,存方法是在此基础上加set
- (float)heightInMeters;
- (void)setHeightInMeters:(float)h;
- (int)weightInKilos;
- (void)setWeightInKilos:(int)w;
//类还拥有一个计算Body Mass Index的方法
- (float)bodyMassIndex;
@end
使用快捷键Ctrl-Command-上箭头返回BNRPerson.m文件。实现.h文件中的方法
#import "BNRPerson.h"
@implementation BNRPerson
//分别实现存取方法
- (float)heightInMeters
{
return _heightInMeters;
}
- (void)setHeightInMeters:(float)h
{
_heightInMeters = h;
}
- (int)weightInKilos
{
return _weightInKilos;
}
- (void)setWeightInKilos:(int)w
{
_weightInKilos = w;
}
//实现计算body mass index的方法
- (float)bodyMassIndex
{
return _weightInKilos / (_heightInMeters * _heightInMeters);
}
@end
main.m主函数文件
#import <Foundation/Foundation.h>
#import "BNRPerson.h"
//上边这一句是引入头文件,这样本文件就可以调用 BNRPerson中的内容。尖括号是表示从苹果库中找,双引号
//表示从当前项目的文件中查找。
int main(int argc, const char * argv[]) {
@autoreleasepool {
//创建实例
BNRPerson *mikey = [[BNRPerson alloc] init];
//用setter方法为实例变量赋值
[mikey setHeightInMeters:96];
[mikey setWeightInKilos:1.8];
//使用getter方法打印出实例变量的值
float height = [mikey heightInMeters];
int weight = [mikey weightInKilos];
NSLog(@"mikey is %.2f meters tall and weights %d kilograms",height,weight);
//使用定制方法打印bmi的值
float bmi = [mikey bodyMassIndex];
NSLog(@"mikey has a BMI of %f",bmi);
}
return 0;
}
2、self
self是指针,指向当前运行方法的对象。
3、前缀
类名一般用3个或以上大写字母作为前缀,避免和其它类库发生命名冲突。比如上述类中的BNR。