- (id)init
{
if (self = [super init]){
//do something init content...
}
}
个人理解就是把初始化的过程放到了方法中,应该说是封装到了方法中,当使用时,只需要调用此方法就能实现对象的初始化.并且,此时不需要setter,getter 方法的声明与实现
直接在对应的实现文件中定义:
- (id)init{
if (self = [super init]) {
engine = [[QYEngine alloc] init];
tires = [[NSMutableArray alloc] initWithCapacity:4];
for (int i = 0; i < 4; i++) {
QYTire *tire = [[QYTire alloc] init];
[tires addObject:tire];
[tire release];
}
}
return self;
}//开箱即用
调用时也非常简单,这届在主函数中调用即可
#import <Foundation/Foundation.h>
#import "QYCar.h"
#import "QYEngine.h"
#import "QYTire.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
//开箱即用
QYCar *myCar = [[QYCar alloc] init];
NSLog(@"Car info: %@",myCar);
[myCar release];
}
return 0;
}
当然,代码并不完整,只需要在相应的实现文件中实现部分打印功能即可
输出的结果如下
Car info: I am engine,(
“I am tire”,
“I am tire”,
“I am tire”,
“I am tire”
)
2015-06-28 21:26:28.068 InitDemo[2276:1416754] car destory
2015-06-28 21:26:29.251 InitDemo[2276:1416754] engine destory
2015-06-28 21:26:29.251 InitDemo[2276:1416754] tire destory
2015-06-28 21:26:30.187 InitDemo[2276:1416754] tire destory
2015-06-28 21:26:31.621 InitDemo[2276:1416754] tire destory
感觉懒加载的方式比较麻烦,他不仅需要 setter,getter 方法的声明和定义,还需要在具体调用时进行现场的初始化方式
懒加载的初始化方式具体实现,在对应的实现文件中:
//懒加载
- (id)init{
self = [super init];
if (self) {
tires = [[NSMutableArray alloc] initWithCapacity:4];
for (int i = 0; i < 4; i++) {
tires[i] = [NSNull null];
}
}
return self;
}
- (void)setEngine:(QYEngine *)newEngine{
[newEngine retain];
[engine release];
engine = newEngine;
}
- (QYEngine*)engine{
return engine;
}
- (void)setTire:(QYTire *)newTire atIndex:(NSUInteger)index
{
//数组的使用会使tires的引用计数器加1
// [newTire retain];
// [tires[index] release];
tires[index] = newTire;
}
- (QYTire*)tireAtIndex:(NSUInteger)index{
return tires[index];
}//懒加载
main() 中的代码也同样不少,其输出结果与上面相同.
int main(int argc, const char * argv[]) {
@autoreleasepool {
//懒加载
QYCar *myCar = [[QYCar alloc] init];
QYEngine *engine = [[QYEngine alloc] init];
[myCar setEngine:engine];
[engine release];
for (int i = 0; i < 4; i++) {
QYTire *tire = [[QYTire alloc] init];
[myCar setTire:tire atIndex:i];
[tire release];
}
NSLog(@"Car info: %@",myCar);
[myCar release];
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/www_nyp_boke/article/details/46786099