重写init方法

// 重写 init方法

当对象创建时我们通常想给对象给一定固定值,那么这时可以重写init

// People类

 1 #import <Foundation/Foundation.h>
 2 // 性别
 3 typedef enum {
 4     SexMan,
 5     SexWoman,
 6 } Sex;
 7 
 8 @interface People : NSObject
 9 {   // 定义实例变量
10     NSString *_name;
11     Sex _sex;
12     int _age;
13 }
14 // property set  get
15 @property NSString *name;
16 @property Sex sex;
17 @property int age;
18 
19 
20 - (void)introduce;
21 @end

//  Person类的实现

#import "People.h"

@implementation People
  // 重写initWith
-(id)initWith:(NSString*)name andSex:(Sex)sex andAge:(int)age{
    
    if (self = [super init]) {
        _name = name;
        _age = age;
        _sex = sex;
    }
    return self;
}

@synthesize name = _name,sex=_sex,age=_age;
- (void)introduce{
    
    NSLog(@"大家好!我叫%@ ,我是一个%d,我今年%d岁",_name,_sex,_age);
}

@end

 // Student类

#import <Foundation/Foundation.h>
#import "People.h"
@interface Student :People

// 专业
@property NSString *major;

// 自定义重写构造
-(id)initWith:(NSString*)name andSex:(Sex)sex andAge:(int)age;
@end

// Student的实现

#import "Student.h"

@implementation Student

// 自定义重写构造
-(id)initWith:(NSString*)name andSex:(Sex)sex andAge:(int)age{
       
    if (self = [super init]) {
        _name = name;
        _age = age;
        _sex = sex;
    }
    return self;
}

// 自我介绍
- (void)introduce{
      
     NSLog(@"大家好!我叫%@ ,我是一个%d,我今年%d岁,专业是%@",self.name,self.sex,self.age,_major);
}
@end

   // main()

int main() {

  // 创建实例对象s1
        Student *s1 = [[Student alloc]initWith:@"小明"      andSex:SexWoman andAge:10];
        s1.major = @"美术";
        [s1 introduce];

    return 0;
}

 // 在初始化时就赋初值

原文地址:https://www.cnblogs.com/jerry1209/p/4243120.html