初识Object-C对象

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 {

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值