请问什么是便利构造器(快速构造器)

Posted 雅之上善若水

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了请问什么是便利构造器(快速构造器)相关的知识,希望对你有一定的参考价值。

今天在查找的时候,发现这个比较浅显易懂,记录下,下面的是人家的回复

 http://bbs.itheima.com/thread-112451-1-1.html

1、便利构造器是一种快速创建对象的方式。它本质上是把初始化方法做了一次封装,方便外界使用

2、便利构造器是一个类方法(以+开头)

类似于Java中的构造方法,
指的是在init的时候,同时给属性变量赋值的方法

比如
@interface Person : NSObject{
    int _age;
    NSString *_name;
}
- (Person *)initWithAge: (int)age andWithName: (NSString *)name; 
+ (Person *)initWithAge: (int)age andWithName: (NSString *)name;//这个类方法在返回Person对象时,就可以给_age和_name赋值,这个就是便利构造器
@end

@implementation Person
- (Person *)initWithAge: (int)age andWithName: (NSString *)name{
    _age = age;
    _name = name;
}
+ (Person *)initWithAge: (int)age andWithName: (NSString *)name
{
    return [[Person alloc] initWithAge:age andWithName:name];
}
@end


int main()
{
    Person *p  = [Person initWithAge: 10 andWithName: @"jason"];// 在init时就赋值了age和name属性

    return 0;
}

  

 

以上是关于请问什么是便利构造器(快速构造器)的主要内容,如果未能解决你的问题,请参考以下文章