zoukankan      html  css  js  c++  java
  • OC基础--构造方法

    OC语言中类的构造方法学了两种:

    一、方法一:[类名  new]  例:[Person  new]

      缺点:可扩展性不强,假如在Person类中有_age 成员变量,在初始化时想让_age 中的值为20,new方法办不到,只能是创建类之后重新赋值

    二、方法二:

          //返回一个已经分配好内存的对象,但是这个对象没有经过初始化

          Person *p = [Person alloc];

          //给指针变量p指向的对象进行初始化操作

          p = [p init];

          合并写法,以后常用:类名 *指针变量名 =  [[类名 alloc] init];例----->Person *p = [[Person alloc] init];

    原理:new方法内部其实做了两件事:

    1.分配内存给对象  +alloc--->类方法

    2.初始化对象  -init--->对象方法,init方法称为构造方法,构造方法其实是用来初始化对象的。

    三、自定义构造函数注意事项-->重写-(id) init方法,其中:

      1)id是万能指针,不要再加上*;id类型能指向任何OC对象

      2)先要初始化父类中的成员变量-->[super init]

      3)将返回的指向父类对象的指针变量赋值给self,也就是当前类-->self = [super init];

      4)一定判断self是否为空if(self != nil) 或者 if(self)-->如果self中没有父类的地址,self就等于0,也就是false

    代码如下:

     1 -(id) init
     2 {
     3     //为了让父类中的成员变量也能初始化
     4     self = [super init];
     5     if (self != nil)//判断self不为空,说明父类初始化成功
     6     {
     7         _age = 20;//想要初始化的属性或其他
     8     }
     9     return self;//构造函数一定是返回当前类
    10 }

    必须简写:-->以后常用的方式

     1 - (id) init
     2 {
     3     // 为了让父类中的成员变量也能初始化
     4     if (self = [super init])
     5     { // 说明父类初始化成功
     6         _age = 20;
     7     }
     8     
     9     return self;
    10 }

    四、自定义构造方法代码实例:

     1 #import <Foundation/Foundation.h>
     2 // 声明
     3 @interface Person : NSObject
     4 {
     5     int _age;
     6 }
     7 - (void) setAge:(int)newAge;
     8 - (int) age;
     9 
    10 // 自定义构造方法
    11 /*
    12  规范:
    13  1.返回值是id类型
    14  2.方法名都以init开头
    15  */
    16 - (id) initWithAge:(int)age;
    17 
    18 @end
    19 
    20 // 实现
    21 @implementation Person
    22 - (void) setAge:(int)newAge
    23 {
    24     _age = newAge;
    25 }
    26 
    27 - (int) age
    28 {
    29     return _age;
    30 }
    31 
    32 - (id) initWithAge:(int)age
    33 {
    34     if (self = [super init])
    35     {
    36         _age = age;
    37     }
    38     return self;
    39 }
    40 
    41 @end
    42 
    43 
    44 int main()
    45 {
    46     /*
    47     [Person new];
    48     [[Person alloc] init];
    49      */
    50     Person *p = [[Person alloc] initWithAge:28];
    51     
    52     NSLog(@"age=%d", [p agec]);
    53     
    54     return 0;
    55 }
  • 相关阅读:
    Chrome cookies folder
    Fat URLs Client Identification
    User Login Client Identification
    Client IP Address Client Identification
    HTTP Headers Client Identification
    The Personal Touch Client Identification 个性化接触 客户识别
    购物车 cookie session
    购物车删除商品,总价变化 innerHTML = ''并没有删除节点,内容仍存在
    453
    购物车-删除单行商品-HTMLTableElement.deleteRow()
  • 原文地址:https://www.cnblogs.com/gchlcc/p/5173623.html
Copyright © 2011-2022 走看看