Help us understand the problem. What is going on with this article?

pluckみたくNSArrayに入ってるNSManagedObjectから特定のプロパティの配列を作りたい時

More than 5 years have passed since last update.

普段Androidな開発友達から質問が来たので。

HogeをNSManagedObjectの派生クラスとします。

@interface Hoge : NSManagedObject
  NSNumber *hoge_id;
  NSNumber *name;
  NSNumber *status;
  Poyo *poyo;
@end

このnameだけの配列が欲しい時どうするか?
ずばりvalueForKeyPath:を使います。

- (NSArray *)namesByStatus:( NSInteger status ){
  NSPredicate *predicate = [NSPredicate predicateWithFormat:@"status = %d", status ];
  NSArray *records = [Hoge findAllByPredicate:predicate];

  return [records valueForKeyPath:@"name"]; // こんだけ
}

さらにHogeに入ったPoyoのnameも欲しい時は?

[records valueForKeyPath:@"poyo.name"]; // こんだけ

「.」で繋げると深いところも取ってこれます。

underscore.js/.phpでいうところのpluckとかそういうのですね。
単純すぎてググりにくいネタなので。

なぜこれで取ってこれるか知りたい人はKVC(Key-Value Coding)辺りを調べるといいかも。

hummer
フリーランスSESエバンジェリスト
https://note.mu/motekawa
engineerlife
技術力をベースに人生を謳歌する人たちのコミュニティです。
https://community.camp-fire.jp/projects/view/280040
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした