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:
我需要在标签中显示数组的计数。为此,我需要将array.count传递给NSString。这是我尝试过的:
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?
它没用。我也尝试用NSMutableString替换NSString,没有结果。所以我的问题是,我该怎么做?
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.
我还尝试将%@替换为%lu,然后在数组计数之前添加(unsigned long)(就像我在NSlog上显示数组计数一样),但这也不起作用。
3 个解决方案
#1
4
NSString *newString = [NSString stringWithFormat:@"Array count = %d", myArray.count];
#2
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
.
您编写代码的原因有点奇怪:Objective C将您的表达式解释为逗号表达式,忽略@“Array count =%@”部分,并将myArray.count的值赋给newString。
This leads to undefined behavior when setText:
tries to copy something from the "pointer" pointed to by myArray.count
.
当setText:尝试从myArray.count指向的“指针”复制某些内容时,这会导致未定义的行为。
#3
1
If you want to be modern:
如果你想成为现代的:
NSString *str = [@(array.count) stringValue];
#1
4
NSString *newString = [NSString stringWithFormat:@"Array count = %d", myArray.count];
#2
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
.
您编写代码的原因有点奇怪:Objective C将您的表达式解释为逗号表达式,忽略@“Array count =%@”部分,并将myArray.count的值赋给newString。
This leads to undefined behavior when setText:
tries to copy something from the "pointer" pointed to by myArray.count
.
当setText:尝试从myArray.count指向的“指针”复制某些内容时,这会导致未定义的行为。
#3
1
If you want to be modern:
如果你想成为现代的:
NSString *str = [@(array.count) stringValue];