Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSSet to string separaing by comma

I have the next code for converting NSSet to string separating by comma:

-(NSString *)toStringSeparatingByComma
{
    NSMutableString *resultString = [NSMutableString new];
    NSEnumerator *enumerator = [self objectEnumerator];
    NSString* value;
    while ((value = [enumerator nextObject])) {
        [resultString appendFormat:[NSString stringWithFormat:@" %@ ,",value]];//1
    }

    NSRange lastComma = [resultString rangeOfString:@"," options:NSBackwardsSearch];
    if(lastComma.location != NSNotFound) {
        resultString = [resultString stringByReplacingCharactersInRange:lastComma  //2
                                                             withString: @""];
    }
    return resultString;
}

It seems that it works, but I get here two warnings:

1. format string is not a string literal (potentially insecure)

2. incompatible pointer types assigning to nsmutablestring from nsstring

How to rewrite it to avoid of warnings?

like image 800
pvllnspk Avatar asked Dec 03 '22 22:12

pvllnspk


2 Answers

There is another way to achieve what you are trying to do with fewer lines of code:

You can get an array of NSSet objects using:

NSArray *myArray = [mySet allObjects];

You can convert the array to a string:

NSString *myStr = [myArray componentsJoinedByString:@","];
like image 62
Hetal Vora Avatar answered Dec 05 '22 12:12

Hetal Vora


stringByReplacingCharactersInRange method's return type NSString. You are assigning it to NSMutableString. Use mutable copy.

resultString = [[resultString stringByReplacingCharactersInRange:lastComma  //2
                                                             withString: @""]mutablecopy]
like image 24
Vignesh Avatar answered Dec 05 '22 12:12

Vignesh