【问题标题】:Get an array of properties from an array of custom objects [duplicate]从一组自定义对象中获取一组属性[重复]
【发布时间】:2015-04-20 21:39:13
【问题描述】:

我有一组自定义对象,比如Messages

这些消息有一个identifierproperty,我想知道从所有identifiers 中获取NSString 数组的最佳方式是什么。

现在,我只是遍历所有对象并将它们的 id 放入另一个数组中,

- (NSArray*)getIdentifiersOf:(NSMutableArray*)array
NSMutableArray *arrIdentifiers = [[NSMutableArray alloc]init];

for (Message *msg in array){
     [arrIdentifiers addObject:msg.identifier];
}

return (NSArray*)arrIdentifiers;

显然这行得通,但它似乎太多余了,我以为你可能会想到别的东西。

例如,我通常只需要发送一个 Id 数组作为参数,我正在考虑类似

myArray[@"identifier"]

可以自动使用数组,但只能使用其中每个对象的特定属性。

【问题讨论】:

    标签: objective-c arrays for-loop optimization


    【解决方案1】:

    使用

    - (id)valueForKey:(NSString *)key:
    

    返回一个数组,其中包含调用 valueForKey 的结果:在数组的每个对象上使用键。

    NSArray * arrIdentifiers = [array valueForKey:@"identifier"];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-09
      • 2018-05-25
      • 2012-06-08
      • 2018-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多