Main.m
#import <Foundation/Foundation.h>
#import "Person.h"
int main(int argc, const char * argv[])
{
//id类型是一个通用类型,可以用来声明任何类型的指针变量(对象)
//void *
//创建一个对象
//两步:申请一块内存 alloc
// 初始化 init
// Person *person = [[Person alloc] init];
Person *person = [[Person alloc] initWithName:@"jack_自定义"];
// Person *person = [[Person alloc] initWithName:@"jack" withAge:34];
//设置值
// [person setName:@"Jack"];
// [person setAge:23];
//等价于
// [person setName:@"jack" withAge:23];
//打印个人信息
[person showInfo];
return 0;
}
Person.h
#import <Foundation/Foundation.h>
@interface Person : NSObject {
NSString *_name; //名字
NSInteger _age; //年龄
}
//自定义初始化方法,将name传入
- (id)initWithName:(NSString *)name;
//自定义初始化方法,将name、age传入
- (id)initWithName:(NSString *)name withAge:(NSInteger)age;
//设置器
- (void)setName:(NSString *)name;
- (void)setAge:(NSInteger)age;
- (void)setName:(NSString *)name withAge:(NSInteger)age;
//打印个人信息的方法
- (void)showInfo;
Person.m
//自定义初始化方法,将name传入
- (id)initWithName:(NSString *)name {
/*
//self 当前对象
//super 父类
self = [super init];
//如果初始化成功,返回当前对象,否则返回nil
if (self != nil) {
_name = name;
}
*/
// return self;
return [self initWithName:name withAge:0];
}
//自定义初始化方法,将name、age传入
- (id)initWithName:(NSString *)name withAge:(NSInteger)age {
//通过父类给当前对象初始化
self = [super init];
//如果初始化成功
if (self != nil) {
_name = name;
_age = age;
}
return self;
}
//设置器
- (void)setName:(NSString *)name {
_name = name;
}
- (void)setAge:(NSInteger)age {
_age = age;
}
- (void)setName:(NSString *)name withAge:(NSInteger)age {
_name = name;
_age = age;
}
//打印个人信息的方法
- (void)showInfo {
//调用当前的方法
// [对象 方法名]
// [self test];
NSLog(@"name:%@ age:%ld",_name,_age);
}
- (void)test {
}