---------------
main.m
---------------
#import
<Foundation/Foundation.h>
@interface
FKCar : NSObject
@property ( nonatomic , copy ) NSString* brand;
@property ( nonatomic , copy ) NSString* model;
@property ( nonatomic , copy ) NSString* color;
- ( id ) initWithBrand:(NSString*) brand model:(NSString*) model;
- ( id ) initWithBrand:(NSString*) brand model:(NSString*) model color:(NSString*) color;
@property ( nonatomic , copy ) NSString* brand;
@property ( nonatomic , copy ) NSString* model;
@property ( nonatomic , copy ) NSString* color;
- ( id ) initWithBrand:(NSString*) brand model:(NSString*) model;
- ( id ) initWithBrand:(NSString*) brand model:(NSString*) model color:(NSString*) color;
@end
@implementation
FKCar
- ( id ) init
{
if ( self = [ super init])
{
self ->_brand = @" 奥迪 " ;
self ->_model = @"Q5" ;
self ->_color = @" 黑色 " ;
}
return self ;
}
- ( id ) initWithBrand:(NSString*) brand model:(NSString*) model
{
if ( self = [ super init])
{
self ->_brand = brand;
self ->_model = model;
self ->_color = @" 黑色 " ;
}
return self ;
}
- ( id ) initWithBrand:(NSString*) brand model:(NSString*) model color:(NSString*) color
{
if ( self = [ self initWithBrand :brand model :model])
{
self ->_color = color;
}
return self ;
}
- ( id ) init
{
if ( self = [ super init])
{
self ->_brand = @" 奥迪 " ;
self ->_model = @"Q5" ;
self ->_color = @" 黑色 " ;
}
return self ;
}
- ( id ) initWithBrand:(NSString*) brand model:(NSString*) model
{
if ( self = [ super init])
{
self ->_brand = brand;
self ->_model = model;
self ->_color = @" 黑色 " ;
}
return self ;
}
- ( id ) initWithBrand:(NSString*) brand model:(NSString*) model color:(NSString*) color
{
if ( self = [ self initWithBrand :brand model :model])
{
self ->_color = color;
}
return self ;
}
@end
int
main()
{
{
FKCar* car1 = [[FKCar alloc] init];
NSLog(@"car1的brand为%@", car1.brand);
NSLog(@"car1的model为%@", car1.model);
NSLog(
@"car1
的
color
为
%@"
, car1.color);
FKCar* car2 = [[FKCar alloc] initWithBrand:
@"
奔驰
"
model:
@"ML350"
];
NSLog(@"car2的brand为%@", car2.brand);
NSLog(
@"car2
的
model
为
%@"
, car2.model);
NSLog(
@"car2
的
color
为
%@"
, car2.color);
FKCar* car3 = [[FKCar alloc] initWithBrand:
@"
宝马
"
model:
@"X5"
color:
@"BLACK"
];
NSLog(@"car3的brand为%@", car3.brand);
NSLog(
@"car3
的
model
为
%@"
, car3.model);
NSLog(
@"car3
的
color
为
%@"
, car3.color);
}
一、编写本节代码的具体步骤:
1.可仿照第二章001节的代码编写步骤,可以把类的接口文件,类的实现文件写在main.m文件中。
二、本节代码涉及到的知识点:
1.initXxx可以根据参数执行更多自定义初始化方法。
2.如果初始化方法B完全包含了初始化方法A,那么就可以直接在初始化方法B中调用初始化方法A。
3.通过使用这些便利的初始化方法,程序可以在创建对象的同时完成初始化,避免对象创建完成之后,
还要再通过调用set方法来设置对象的属性值。