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

时间:2016-01-20 04:41:50

标签: ios filter properties nsarray

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

例如NSString CommaSeperted = @"1,3,5"等。

2 个答案:

答案 0 :(得分:1)

NSArray的类别:

@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")];

答案 1 :(得分:0)

试试这个

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

commaSeparatedStringOfID将是您需要的字符串。