• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

Objective-C构造方法

武飞扬头像
Zyryck
帮助1

构造方法在创建(实例化)对象的时候,自动调用的方法

带参构造方法

-(instancetype)initWith...

  1.  
    #import <Foundation/Foundation.h>
  2.  
     
  3.  
    @interface Person : NSObject{
  4.  
    NSString* _name;
  5.  
    NSInteger _age;
  6.  
    }
  7.  
    //init方法是系统自带的,实现在NSObject类里
  8.  
    //自定义的构造方法需要显示申明
  9.  
    - (instancetype)initWithName:(NSString*)name;
  10.  
    - (instancetype)initWithName:(NSString*)name age:(NSInteger)age;
  11.  
    -(void)showMessage;
  12.  
    @end
  13.  
     
  14.  
    @implementation Person
  15.  
    -(instancetype)init{
  16.  
    //self是一个指针 它表示当前调用该方法的对象本身
  17.  
    //super 用来调用父类方法的关键字
  18.  
    self = [super init];
  19.  
    if(self){
  20.  
    NSLog(@"系统自带的构造方法");
  21.  
    _name = @"no name";
  22.  
    _age = 0;
  23.  
    }
  24.  
    return self;
  25.  
    }
  26.  
    //自定义的需要显示申明
  27.  
    - (instancetype)initWithName:(NSString*)name{
  28.  
    self = [super init];
  29.  
    if(self){
  30.  
    NSLog(@"调用自定义的构造函数");
  31.  
    _name = name;
  32.  
    }
  33.  
    return self;
  34.  
    }
  35.  
    - (instancetype)initWithName:(NSString *)name age:(NSInteger)age{
  36.  
    self = [super init];
  37.  
    if(self){
  38.  
    _name = name;
  39.  
    _age = age;
  40.  
    }
  41.  
    return self;
  42.  
    }
  43.  
    - (void)showMessage{
  44.  
    NSLog(@"name:%@ age:%ld",_name,_age);
  45.  
    }
  46.  
    @end
  47.  
     
  48.  
    int main(int argc, const char * argv[]) {
  49.  
    @autoreleasepool {
  50.  
    Person* p1 = [Person new];
  51.  
    Person* p2 = [[Person alloc] initWithName:@"dancer"];
  52.  
    Person* p3 = [[Person alloc] initWithName:@"XiaoMing" age:19];
  53.  
    [p1 showMessage];
  54.  
    [p2 showMessage];
  55.  
    [p3 showMessage];
  56.  
    }
  57.  
    return 0;
  58.  
    }
学新通

无参构造方法

init->NSObject

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgaakih
系列文章
更多 icon
同类精品
更多 icon
继续加载