初始化的3种方法
//重写的init方法
//使用遍历初始化函数 初始化
//使用构造遍历器 初始化
mian.h
#import <Foundation/Foundation.h>
#import "Student.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
//重写的init方法
Student *stu3 = [[Student alloc] init];
[stu3 sayHi];
//使用遍历初始化函数 初始化
Student *stu = [[Student alloc] initWithName:@"张三" andAge:18 andHobby:@"玩游戏" andAddr:@"月球"];
[stu sayHi];
//使用构造遍历器 初始化
Student *stu1 = [Student studentWithName:@"lisi" andAge:18 andHobby:@"23" andAddr:@"dd"];
[stu1 sayHi];
}
return 0;
}
Student.h
#import <Foundation/Foundation.h>
@interface Student : NSObject
{
NSString * _name;
int _age;
NSString * _hobby;
NSString * _addr;
}
#pragma mark 遍历构造器
/**
遍历构造器
*/
+(Student *)studentWithName:(NSString *)name andAge:(int)age andHobby:(NSString *)hobby andAddr:(NSString *)addr;
#pragma mark 遍历出使唤函数
/**
遍历初始化函数
*/
-(Student *)initWithName:(NSString *)name andAge:(int)age andHobby:(NSString *)hobby andAddr:(NSString *)addr;
#pragma mark 功能函数
-(void)sayHi;
@end
Student.m
#import "Student.h"
@implementation Student
/**
重写的init的方法
*/
-(instancetype)init
{
if (self = [super init]) {
_name = @"莉丝";
}
return self;
}
-(Student *)initWithName:(NSString *)name andAge:(int)age andHobby:(NSString *)hobby andAddr:(NSString *)addr
{
if (self=[super init]) {
_name = name;
_age = age;
_hobby = hobby;
_addr = addr;
}
return self;
}
+(Student *)studentWithName:(NSString *)name andAge:(int)age andHobby:(NSString *)hobby andAddr:(NSString *)addr
{
Student *stu = [[Student alloc] initWithName:name andAge:age andHobby:hobby andAddr:addr];
return stu;
}
-(void)sayHi
{
NSLog(@"%@向你说hello",_name);
}
@end