pvllnspk
pvllnspk

Reputation: 5767

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?

Upvotes: 4

Views: 3654

Answers (2)

Hetal Vora
Hetal Vora

Reputation: 3361

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

Upvotes: 16

Vignesh
Vignesh

Reputation: 10251

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

resultString = [[resultString stringByReplacingCharactersInRange:lastComma  //2
                                                             withString: @""]mutablecopy]

Upvotes: 1

Related Questions