LoginSignup
9
9

More than 5 years have passed since last update.

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

Last updated at Posted at 2014-02-26

普段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)辺りを調べるといいかも。

9
9
1

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
9
9