I have a Array of custom objects with object having following properties optionID,OptionText
. I want to get comma separated string for the optionID
property. What would be the best approach to do this in iOS SDK
.
for example NSString CommaSeperted = @"1,3,5"
etc.
Category to 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
Example:
@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")];