0

I'm trying to display all string items within an array in a text label.

self.latestTenThrows.text = [NSString stringWithFormat:@"%@", self.savedThrowsArray];

The output of this in the view is however:

(
    "4 + 4 + 3 + 2 + 1 = 14",
    "6 + 5 + 4 + 5 + 2 = 22",
    "2 + 3 + 5 + 1 + 6 = 17"
)

What should i do to get it to look like this:

4 + 4 + 3 + 2 + 1 = 14
6 + 5 + 4 + 5 + 2 = 22
2 + 3 + 5 + 1 + 6 = 17

3 Answers 3

3

See the Apple documentation for NSArray there is a method you can use to concatenate all the array elements with an inserted string:

NSString *s = [self.savedThrowsArray componentsJoinedByString: @"\n"];
self.latestTenThrows.text = s;
Sign up to request clarification or add additional context in comments.

Comments

1

What you are seeing when you log the entire array at once is a formatted description of the array. If you want to format the array's contents on your own, extract each object and log it, like this:

for (NSString *line in self.savedThrowsArray) {
    NSLog(@"%@", line);
}

You can change the @"%@" to match whatever output format you want, such as including leading or trailing spaces, or additional content.

If you want to composite all of the results into one string, that can be done like this:

NSMutableString *mStr = [[NSMutableString alloc] init];
for (NSString *line in self.savedThrowsArray) {
    [mStr appendFormat:@"%@\n", line];
}
self.latestTenThrows.text = mStr;

2 Comments

You forgot the /N at the end. But this is the answer. Build a string before the for loop. And after the for loop set the string to the textview. That's it.
Ah I see, you are assigning the resulting string to a control. I updated my answer with a way to build a string line-by-line.
0

There is an NSArray method componentsJoinedByString

Assuming each element in your array is a string like one of the lines you've shown, you could use code like this:

NSString *combinedString = [componentsJoinedByString: @"\n"];
self.latestTenThrows.text = combinedString;

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.