gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 01:18:20 26 4
gpt4 key购买 nike

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

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

最佳答案

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

关于ios - 从自定义对象数组中获取属性的逗号分隔字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34891747/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com