Objective-C set default value for a property

前端 未结 7 611
感情败类
感情败类 2021-02-03 20:30

I\'m making an app, and I have a class with quite a lot properties and I was wondering if it was possible to give them a default value. Because if I make an init method, it\'s a

7条回答
  •  北荒
    北荒 (楼主)
    2021-02-03 21:22

    - (id)init
    {
        self = [super init];
        if (self != nil) {
            [self commonInit];
        }
    
        return self;
    }
    
    - (id)initWithFrame:(CGRect)frame
    {
        self = [super initWithFrame:frame];
        if (self != nil) {
            [self commonInit];
        }
    
        return self;
    }
    
    -(instancetype)initWithCoder:(NSCoder *)aDecoder { //nib init
        self = [super initWithCoder:aDecoder];
        if (self != nil) {
            [self commonInit];
        }
        return self;
    }
    

    You can set default value and do default logic in commonInit function if the object is a view. If it's not view, you can do it in the init function in my opinion.

提交回复
热议问题