1、构造方法
//Book.h
#import <Foundation/Foundation.h>
@interface Book : NSObject {
int _ID;
double _price;
}
//set方法和get方法
- (void)setID:(int)ID;
- (int)ID;
- (void)setPrice:(double)price;
- (double)price;
//构造方法一般以init开头
- (id)initWithPrice:(double)price;
- (id)initWithID:(int)ID andPrice:(double)price;
@end
//Book.m
#import "Book.h"
@implementation Book
- (void)setID:(int)ID {
_ID = ID;
}
- (int)ID {
return _ID;
}
- (void)setPrice:(double)price {
_price = price;
}
- (double)price {
return _price;
}
- (id)initWithPrice:(double)price {
//先调用父类的init方法,返回一个初始化对象赋值给self
//再判断self是否为空,不为空才初始化_price
if (self = [super init]) {
//_price = price;
self.price = price; //也可以这样写(调用set方法)
}
return self;
}
- (id)initWithID:(int)ID andPrice:(double)price {
if (self = [super init]) {
self.ID = ID;
self.price = price;
}
return self;
}
@end
//main.m
#import <Foundation/Foundation.h>
#import "Book.h"
int main()
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
//例1:
//调用构造方法initWithPrice
Book *b = [[Book alloc] initWithPrice:32.55555555];
//保留两位小数输出
NSLog(@"price is %.2f", b.price);
//例2:
//构造的同时初始化多个变量
Book *b2 = [[Book alloc] initWithID:1001 andPrice:105.12345];
NSLog(@"id is %i, price is %.2f", b2.ID, b2.price);
[b release];
[b2 release];
[pool drain];
return 0;
}
运行结果:
2、description方法
//Book.h
#import <Foundation/Foundation.h>
@interface Book : NSObject {
double _price;
}
//set方法和get方法
- (void)setPrice:(double)price;
- (double)price;
@end
//Book.m
#import "Book.h"
@implementation Book
- (void)setPrice:(double)price {
_price = price;
}
- (double)price {
return _price;
}
@end
//main.m
#import <Foundation/Foundation.h>
#import "Book.h"
int main()
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
Book *b = [[Book alloc] init];
//"%@"输出调用对象的description方法
//这里没重写description方法,所以是默认输出类名和16进制地址
NSLog(@"%@", b);
[b release];
[pool drain];
return 0;
}
运行结果:
3、重写description方法
//Book.m
#import "Book.h"
@implementation Book
- (void)setPrice:(double)price {
_price = price;
}
- (double)price {
return _price;
}
//重写description方法
- (NSString *)description { //NSString 是OC对象的字符串,要加*号是因为OC的所有对象都是指针
NSString *s = [NSString stringWithFormat:@"price is %.2f", _price];
return s;
}
@end
运行结果: