Objective-c初始化方法

Animal.h
#import 

@interface Animal : NSObject
@property (nonatomic,retain) NSString *breed;
@property (nonatomic,retain) NSString *name;
@property (nonatomic,retain) NSString *habit;
- (instancetype)initWithBreed:(NSString *)breed name:(NSString *)name habit:(NSString *)habit;

+ (instancetype)animilWithBreed:(NSString *)breed name:(NSString *)name habit:(NSString *)habit;

@end
Animal.m
#import "Animal.h"

@implementation Animal
- (instancetype)initWithBreed:(NSString *)breed name:(NSString *)name habit:(NSString *)habit {
    self  = [super init];
    if (self) {
        _breed = breed;
        _name = name;
        _habit = habit;
        
    }
    return self;
}
+ (instancetype)animilWithBreed:(NSString *)breed name:(NSString *)name habit:(NSString *)habit {
    return [[Animal alloc] initWithBreed:breed name:name habit:habit];
    
    }
 @end

main.m
#import 
#import "Animal.h"
Animal *animal = [[Animal alloc] initWithBreed:@"宠物狗" name:@"贵兵犬" habit:@"吃饭 睡觉"];
    NSLog(@"%@,%@,%@",animal.breed,animal.name,animal.habit);

你可能感兴趣的:(Objective-c初始化方法)