Ios 从自定义对象数组中获取属性的逗号分隔字符串

Ios 从自定义对象数组中获取属性的逗号分隔字符串,ios,filter,properties,nsarray,Ios,Filter,Properties,Nsarray,我有一个自定义对象数组,该对象具有以下属性optionID、OptionText。我想为optionID属性获取逗号分隔的字符串。在iOS SDK中执行此操作的最佳方法是什么 例如,NSString CommaSeperted=@“1,3,5”等 @implementation NSArray(CustomAdditions) - (NSString *)commaSeparatedStringWithSelector:(SEL)aSelector { NSMutableArray *

我有一个自定义对象数组,该对象具有以下属性
optionID、OptionText
。我想为
optionID
属性获取逗号分隔的字符串。在
iOS SDK
中执行此操作的最佳方法是什么

例如,NSString CommaSeperted=@“1,3,5”等

@implementation NSArray(CustomAdditions)

- (NSString *)commaSeparatedStringWithSelector:(SEL)aSelector
{
    NSMutableArray *objects = [NSMutableArray array];

    for (id obj in self)
    {
        if ([obj respondsToSelector:aSelector]) {
            IMP method = [obj methodForSelector:aSelector];
            id (*func)(id, SEL) = (void *)method;
            id customObj = func(obj, aSelector);
            if (customObj && [customObj isKindOfClass:[NSString class]]) {
                [objects addObject:customObj];
            }
        }
    }
    return [objects componentsJoinedByString:@","];
}


@end
例如:

@implementation NSDictionary(Test)

- (NSString*)optionID
{
    return [self objectForKey:@"optionID"];
}

- (NSString*)OptionText
{
    return [self objectForKey:@"OptionText"];
}

@end

NSArray *customObjects = @[@{@"optionID": @"id1", @"OptionText": @"text1" }, @{@"optionID" : @"id2", @"OptionText": @"text2"}];//List of Your custom objects

NSString *commaSeparatedOptionIDs = [customObjects commaSeparatedStringWithSelector:NSSelectorFromString(@"optionID")];

NSString *commaSeparatedOptionTexts = [customObjects commaSeparatedStringWithSelector:NSSelectorFromString(@"OptionText")];
试试这个

NSString *commaSeparatedStringOfID = @"";
for (CustomClass *object in yourArray){
commaSeparatedStringOfID = [commaSeparatedStringOfID stringByAppendingString:[NSString stringWithFormat:@"%@,"]];
}
// removing last comma
commaSeparatedStringOfID = [commaSeparatedStringOfID substringToIndex:[commaSeparatedStringOfID length]-1];

commaSeparatedStringOfID
将是您所需的字符串。

是否可以创建一个类别并获取这些类别,而无需为具有不同对象的所有数组添加函数?我有许多自定义对象子类NSObject。例如兴趣、语言等都有属性名OptionID、OptionText。你能更新分类吗?