1

私は2つのオブジェクトを持っています:

@interface AObject : NSObject

@property NSArray *bObjects;

@end

 

@interface BObject : NSObject

@property NSString *name;

@end

のインスタンスでキー値コーディングを使用すると、 ( ) のリストと' 名前 ( )AObjectのリストを取得できます。bObjects@"self.bObjects"bObjects@"self.bObjects.name"

しかし、私が欲しいのはbObjects. 私の直感は、キー値のコーディングは、次のようにリストの添え字をサポートする必要があるということです: @"bObjects[0].name".

しかし、それは存在しないようです。単一のエンティティを取得するにはどうすればよいですか。キー値コーディングを使用したAObjectの最初の の名前?BObject

脚注: 前回の質問で、NSPredicate と KV コーディングを愚かにも混同していたことに気付きました。

4

2 に答える 2

1

Martin R がコメントで述べたように、現時点で最良の選択肢は、クラスにfirstBObjectプロパティを作成することです。AObject

AObject.h/m

@class BObject;

@interface AObject : NSObject
+ (AObject*)aObjectWithBObjects:(NSArray*)bObjects;
@property NSArray *bObjects;
@property (nonatomic, readonly) BObject *firstBObject;
@end

@implementation AObject
+ (AObject*)aObjectWithBObjects:(NSArray*)bObjects
{
    AObject *ao = [[self alloc] init];
    ao.bObjects = bObjects;
    return ao;
}
- (BObject*)firstBObject
{
    return [self.bObjects count] > 0 ? [self.bObjects objectAtIndex:0] : nil;
}
@end

BObject.h/m

@interface BObject : NSObject
+ (BObject*)bObjectWithName:(NSString*)name;
@property NSString *name;
@end

@implementation BObject
+ (BObject*)bObjectWithName:(NSString *)name
{
    BObject *bo = [[self alloc] init];
    bo.name = name;
    return bo;
}
@end

使用法:

NSArray *aobjects = @[
                      [AObject aObjectWithBObjects:@[
                       [BObject bObjectWithName:@"A1B1"],
                       [BObject bObjectWithName:@"A1B2"],
                       [BObject bObjectWithName:@"A1B3"],
                       [BObject bObjectWithName:@"A1B4"]
                       ]],
                      [AObject aObjectWithBObjects:@[
                       [BObject bObjectWithName:@"A2B1"],
                       [BObject bObjectWithName:@"A2B2"],
                       [BObject bObjectWithName:@"A2B3"],
                       [BObject bObjectWithName:@"A2B4"]
                       ]],
                      [AObject aObjectWithBObjects:@[
                       [BObject bObjectWithName:@"A3B1"],
                       [BObject bObjectWithName:@"A3B2"],
                       [BObject bObjectWithName:@"A3B3"],
                       [BObject bObjectWithName:@"A3B4"]
                       ]]
                      ];
NSLog(@"%@", [aobjects valueForKeyPath:@"firstBObject.name"]);

結果

(
A1B1、
A2B1、
A3B1
)

于 2013-08-22T19:32:23.423 に答える