通过一段代码的编写和实现来简单说明OC程序的创建过程。部分笔记结合在代码的注释中。
.h文件存放类,函数声明。
#import <Foundation/Foundation.h>
@interface Dog : NSObject
{ // 写字段 注明成员变量
@protected
int ID;
@public
int age;
@private
float price;
}
// 凡是以initXXXX开头的都是构造函数
- (id) init;
// 函数名为init 不带参数
- (id) initWithID:(int)newID;
// 函数名为 initWithID: 带一个int的参数
- (id) initWithID:(int)newID andAge:(int)newAge;
// 函数名为 initWithID:andAge: 带2个参数,都为int
- (id) initWithID:(int)newID andAge:(int)newAge andOrice:(float)newPrice;
// 函数名为initWithID:andAge:andPrice 带有3个参数,都是int
- (void) setID:(int)newID;
- (int) getID;
// set/get ID
- (void) setAge:(int)newAge;
- (int) getAge;
- (void) setPrice:(int)newPrice;
- (float) getPrice;
- (void) setID:(int)newID andAge:(int)newAge;
// setID:andAge: 2个参数
- (void) setID:(int)newID andAge:(int)newAge andPrice:(float)newPrice;
// setID:andAge:andPrice: 3个参数
@end
.m文件存放类的具体实现。
#import "Dog.h"
@implementation Dog
- (id) init
{
return [self initWithID:1];
}
- (id) initWithID:(int)newID
{
return [self initWithID:newID andAge:2];
}
- (id) initWithID:(int)newID andAge:(int)newAge
{
return [self initWithID:newID andAge:newAge andOrice:60.0f];
}
- (id) initWithID:(int)newID andAge:(int)newAge andOrice:(float)newPrice
{
self = [super init];
if (self) {
ID = newID;
age = newAge;
price = newPrice;
}
return self;
}
- (void) setID:(int)newID
{
ID = newID;
}
- (int) getID
{
return ID;
}
- (void) setAge:(int)newAge
{
age = newAge;
}
- (int) getAge
{
return age;
}
- (void) setPrice:(int)newPrice
{
price = newPrice;
}
- (float) getPrice
{
return price;
}
- (void) setID:(int)newID andAge:(int)newAge
{
ID = newID;
age = newAge;
}
- (void) setID:(int)newID andAge:(int)newAge andPrice:(float)newPrice
{
ID = newID;
age = newAge;
price = newPrice;
}
@end
main函数包含.h头文件,调用类并创建对象。
#import <Foundation/Foundation.h>
#import "Dog.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Dog *dog1 = [[Dog alloc] init];
// 无参数的初始化
int ID = [dog1 getID]; // 用三个变量接收成员变量并打印
int age = [dog1 getAge];
float price = [dog1 getPrice];
printf("dog1 id is %d age is %d price is %f\n", ID, age, price);
// 打印结果:dog1 id is 1 age is 2 price is 60.000000
Dog *dog2 = [[Dog alloc] initWithID:100 andAge:36 andOrice:68.88];
ID = [dog2 getID];
age = [dog2 getAge];
price = [dog2 getPrice];
printf("dog2 id is %d age is %d price is %f\n", ID, age, price);
// dog2 id is 100 age is 36 price is 68.879997
[dog2 setID:2012 andAge:38 andPrice:87.2];
ID = [dog2 getID];
age = [dog2 getAge];
price = [dog2 getPrice];
printf("dog2 new id is %d age is %d price is %f\n", ID, age, price);
// dog2 new id is 2012 age is 38 price is 87.199997
}
return 0;
}