oc 便利初始化、便利构造器

便利初始化
main.m
#import <Foundation/Foundation.h>
#import
"Chushi.h"
int main( int argc, const char * argv[]) {
   
@autoreleasepool {
       
// 初始化,产生一个对象,将其赋值给实例变量(对象)
      
// Chushi *z=[[Chushi alloc ] init];
     
       
// 便利初始化方法的调用
       
Chushi *z=[[ Chushi alloc ] initWithName : @" 2" ];
       
       
NSLog ( @"--%@" ,z);
        [z
sayHi ];
    }
   
return 0 ;
}

Chushi.h
// 便利初始化:在初始化的同时给成员变量赋值
#import <Foundation/Foundation.h>

@interface Chushi : NSObject {
   
NSString *name;
}
// 便利初始化命名: -( 类名 *)initWith 成员变量名:(类型)参数名
-(
Chushi *)initWithName:( NSString *)newName;
-(
void )sayHi;
@end

Chushi.m
#import "Chushi.h"

@implementation Chushi


//-(Audi *)initWithCarname:(NSString *)newName andinitWithModel:(NSString *)newModel andinitWithPrice:(int) newPrice;多参数
-( Chushi *)initWithName:( NSString *)newName{
   
   
self = [ super init ]; // 通过父类调用 init 初始化方法,产生一个方法,此处 self 就是类的对象
   
   
// 判断是否初始化成功,未初始化之前, self nil
   
if ( self ) { // 如果初始化成功,则进行相关操作(如:给成员赋值)
       
name =newName;
    }
   
   
// 将初始化完成后的对象返回
   
return self ;
}
-(
void )sayHi{
   
NSLog ( @"%@" , name );
}

     (     
     额外添加的多参数打印示例,
-( NSString *)description{
    return [NSString stringWithFormat:@"我的名字是:%@,年龄是:%d",name, price]; // 显示多个参数
}
     )

-( NSString *)description{ // 类的描述方法,默认返回对象的地址,我们可以对其重写,实现我们想要的效果
   
return name ;
}
@end


便 :

main.m
#import <Foundation/Foundation.h>
#import "Student.h"
int main( int argc, const char * argv[]) {
   
@autoreleasepool {
       
// 便利构造器的调用, [ 类名   方法名 ];
       
Student *stu = [ Student studentWithName : @ pp " andAge : 20 ];
       
       
NSLog ( @"%@" ,stu);
    }
   
return 0 ;
}

Student.h
// 便利构造器:通过类方式实现对象的初始化以及成员变量的赋值
#import <Foundation/Foundation.h>

@interface Student : NSObject {
   
NSString *name;
   
int       age;
}
- ( Student *)initWithName:( NSString *)newName1 andAge:( int )newAge1;

// 遍历构造器方法声明: +( 类名 *) 类名小写 With 变量名
+ (Student *)studentWithName:(NSString *)newName andAge:(int)newAge;
@end

Student.m
#import "Student.h"
@implementation Student
-( Student *)initWithName:( NSString *)newName1 andAge:( int )newAge1{
   
self = [ super init ];
   
if ( self ) {
       
name = newName1;
       
age = newAge1;
    }
   
return self ;
}

// 便利构造器实现:
+(
Student *)studentWithName:( NSString *)newName andAge:( int )newAge{
   
  
// 初始化一个对象


//     原始的初始化方法
   
Student *stu = [[ Student alloc ] init ];
   
// 给成员变量赋值(类方法里无法直接使用成员变量,因为成员变量属于对象)
    stu->
name = newName;
    stu->
age = newAge;

   
//    // 遍历初始化
  
// Student *stu = [[Student alloc] initWithName:newName andAge:newAge];
   
NSLog ( @"---%@" ,stu-> name );
   
// 将初始化完成后的对象返回
   
return stu;
}
-(
NSString *)description{
   
return name ;
}
@end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值