2

I'm trying to display the items in an array using the following:

NSString *alertString = [NSString stringWithFormat:@"%@", path];

Which works fine, but when I display the string it gets displayed in the following way:

(
A,
B,
C,
D
)

Is there a way to get it to display in a different way, such as all on one line and without brackets, commas or line returns like this:

A B C D

2 Answers 2

13

You have a few options. It looks like the objects within the array have a description method that prints them the way you want to, so it may be as simple as using:

NSString *alertString = [path componentsJoinedByString:@" "];

If not, you could consider something like this:

NSMutableString *s = [NSMutableString string];
[path enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    [s appendString:@" "];
    [s appendString:[obj someMethodThatFormatsTheObject]];
}];
NSString *alertString = [NSString stringWithString:s];

Or even:

NSMutableArray *a = [NSMutableArray array];
[path enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    [a addObject:[obj sometMethodThatFormatsTheObject]];
}];
NSString *alertString = [a componentsJoinedByString:@" "];
Sign up to request clarification or add additional context in comments.

1 Comment

Picked this one purely because it was detailed. Thanks for the help :)
9

If that path is an NSArray, you could use the -componentsJoinedByString: method to concatenate all strings in the array with the desired separator.

NSString* alertString = [path componentsJoinedByString:@" "];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.