0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Objctive-C]alloc省略型イニシャライザの実装

Posted at

例えば、Peopleというモデルを生成する際にinitWithName:みたいなイニシャライザを作ったとします。
そうすると、生成時は
People*people = [[People alloc] initWithName:@"Yuki"]
みたいになります。

ところで、Objective-Cでは段々とこのallocってわざわざ書く必要あんの…?という流れになってきています。
例えばnewは恐らく内部で


+ (instancetype)new{
    return [[People alloc] init];
}

となっています。
引数を渡す場合も

People *people = [People peopleWithName:@"Yuri"];

って書けるといいですよね。
newの例でお分かりかと思いますが、
+ (instancetype)peopleWithName:(NSString*)name
というメソッドを作り、内部でinitWithNameを呼べばいいのですね。

+ (instancetype)peopleWithStatus:(NSString *)name{
    return [[People alloc] initWithName:name];
}

いじょ!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?