oc中的构造方法和description方法,变量的作用呀

1.构造方法的声明和实现

//声明
- (id) initWithAge:(int) age andNo: (int) no;


//实现
- (id) initWithAge:(int) age andNo: (int) no
{
     self=[super init];//调用父类的init方法初始化
     //判断对象是否为空 也可以直接写if(self) 或 if(self=[super init])
     if(self!=nil)
     {
          _age=age;
          _no=no;
     }  
    return  self;  
}


//调用
Student *stu=[[Student alloc] initWithAge:20 andNo:1]

2.description方法相当于java中的toString方法,用来打印对象的,一般都是重写的

- (void) description
{
    NSLog();
}

只要类重写了这个方法用@打印对象时,就会自动调用这个方法。

原文地址:https://www.cnblogs.com/hui1107464497/p/4539401.html