1

I need to display the count of a array in a label. To do that I need to pass the array.count to an NSString. This is what I have tried:

if (myArray.count > 0 ) {
   NSString *newString = @"Array count = %@", myArray.count; 
   [_myLabel setText:newString];
} 

It didn't work. I also tried to replace the NSString with an NSMutableString, no results there. So my question is, how do i do that?

I also tried to replace the %@, for %lu, and then add the (unsigned long) before the array count (just like I do to display the array count on a NSlog), but this did not work either.

3 Answers 3

4
NSString *newString = [NSString stringWithFormat:@"Array count = %d", myArray.count];
Sign up to request clarification or add additional context in comments.

Comments

2

Like this:

NSString *newString = [NSString stringWithFormat:@"Array count = %lu", myArray.count]; 

The reason why your code even compiled is somewhat strange: Objective C interpreted your expression as a comma expression, ignoring the @"Array count = %@" portion, and assigning the value of myArray.count to newString.

This leads to undefined behavior when setText: tries to copy something from the "pointer" pointed to by myArray.count.

Comments

1

If you want to be modern:

NSString *str = [@(array.count) stringValue];

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.