1. 在Student.h声明构造方法:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    #import <Foundation/Foundation.h>
    @interface Student : NSObject {
    int _age; //变量
    }
    - (void)setAge:(int)age; //set方法
    - (int)age; //get方法
    - (id)initWithAge:(int)age; //构造方法
    @end
  2. 在Student.m中实现构造方法:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    #import “Student.h"
    @implementation Student
    - (void)setAge:(int)age {
    _age = age;
    }
    - (int)age {
    return _age;
    }
    //构造方法实现
    - (id)initWithAge:(int)age {
    if (self = [super init]) { //调用父类默认构造方法赋值给self变量
    _age = age;
    }
    return self;
    }
    @end

构造方法规则:方法返回id(id表示任意对象),并且名字以init +首字母大写开头+其他 为准则

  1. 调用上述自定义的构造方法

    1
    Student *stu = [[Student alloc] initWithAge:27];
  2. 输出对象日志信息,打印对象必须使用%@:

    1
    NSLog(@"%@", stu);
  3. 重写description方法,相当于java的toString方法,输出对象日志时自动调用

    1
    2
    3
    - (NSString *)description {
    return [NSString stringWithFormat:@"age=%i", _age];
    }
文章目录