ios - 键值编码获取列表中的元素

标签 ios objective-c key-value-coding

我有两个对象:

@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 编码混为一谈。

最佳答案

正如 Martin R 在评论中提到的,目前最好的选择是在 AObject 类中创建一个 firstBObject 属性。

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
)

关于ios - 键值编码获取列表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18387758/

相关文章:

ios - JavaScriptCore 框架在 iOS 上的可用性

ios - 你如何以编程方式从 View Controller 中画一条线?

ios - Objective-C - 检测先前模态视图的实例

ios - Sprite 套件中的 UIImageView

cocoa-touch - 如何在iPhone的UIView上附加键值对?

iOS 如何使用谓词或 KVC 将对象的多个属性转储到字典中?

ios - nsarray使用键值集合运算符

iphone - 如何使像素适合位图UIImage中的指定颜色?

ios - 使用通用 URL 方案向 Google 导航添加多个站点

ios - Facebook Swift SDK - 消息对话框