026.initWith 更多初始化方法

---------------  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;
@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 ;
}
@end

int main()
{
    FKCar* car1 = [[FKCar alloc] init];
    NSLog(@"car1brand%@", car1.brand);
    NSLog(@"car1model%@", car1.model);
    NSLog( @"car1 color %@" , car1.color);
    FKCar* car2 = [[FKCar alloc] initWithBrand: @" 奔驰 " model: @"ML350" ];
    NSLog(@"car2brand%@", car2.brand);
    NSLog( @"car2 model %@" , car2.model);
    NSLog( @"car2 color %@" , car2.color);
    FKCar* car3 = [[FKCar alloc] initWithBrand: @" 宝马 " model: @"X5" color: @"BLACK" ];
    NSLog(@"car3brand%@", 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方法来设置对象的属性值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值