ios-如何将NSString转换为NSArray

这个问题已经在这里有了答案:            >            Comma-separated string to NSArray in Objective-C                                    2个
我有一个像

NSString* str = @"[90, 5, 6]";

我需要将其转换为数组

NSArray * numbers = [90, 5 , 6];

我做了很长一段路:


+ (NSArray*) stringToArray:(NSString*)str
{
    NSString *sep = @"[,";
    NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:sep];
    NSArray *temp=[str componentsSeparatedByCharactersInSet:set];

    NSMutableArray* numbers = [[NSMutableArray alloc] init];
    for (NSString* s in temp) {
        NSNumber *n = [NSNumber numberWithInteger:[s integerValue]];
        [numbers addObject:n];
    }

    return numbers;
}

是否有任何整洁而快捷的方法来进行这种转换?

谢谢

最佳答案
首先从字符串中删除不需要的字符,例如空格和花括号:

NSString* str = @"[90, 5, 6]";
NSCharacterSet* characterSet = [[NSCharacterSet
                                 characterSetWithCharactersInString:@"0123456789,"] invertedSet];
NSString* newString = [[str componentsSeparatedByCharactersInSet:characterSet]
                       componentsJoinedByString:@""];

您将拥有一个像这样的字符串:90,5,6.然后只需使用逗号分割并转换为NSNumber即可:

NSArray* arrayOfStrings = [newString componentsSeparatedByString:@","];
NSMutableArray* arrayOfNumbers = [NSMutableArray arrayWithCapacity:arrayOfStrings.count];
for (NSString* string in arrayOfStrings) {
    [arrayOfNumbers addObject:[NSDecimalNumber decimalNumberWithString:string]];
}

使用this response的NSString类别可以简化为:

NSArray* arrayOfStrings = [newString componentsSeparatedByString:@","];
NSArray* arrayOfNumbers = [arrayOfStrings valueForKey: @"decimalNumberValue"];

转载注明原文:ios-如何将NSString转换为NSArray - 代码日志