3

I'm trying to cast a NSUInteger to a string so I can print a message. From searching, it seems like I need to use stringWithFormat, but I am getting an error that an implicit cast not allowed with ARC.

Here's the line in question:

NSString *text = [[NSString stringWithFormat: (@"%li",  NSUInteger)];

I've tried changing the format specifier to %lu with no help.

Thanks.

tangobango
  • 381
  • 1
  • 4
  • 17
  • 1
    try [NSString stringWithFormat: @"%li",unsignedinteger]; – limon May 25 '14 at 17:04
  • 2
    Why the parentheses? Where's the value you are trying to format? – rmaddy May 25 '14 at 17:15
  • 1
    @matt - wrong duplicate. This question boils down to a problem with the invalid parentheses and not a problem with type conversions. – rmaddy May 25 '14 at 17:28
  • @rmaddy the duplicate shows the exact correct form of the line of code to use – matt May 25 '14 at 17:29
  • 3
    @matt But it's a different question. Just because the answer is similar does not make it a duplicate question. – rmaddy May 25 '14 at 17:36
  • @matt Does it matter that the duplicate doesn't show on search becasue the error messages are different? The other one doesn't reference ARC which seems to be the issue that the error addresses. – tangobango May 25 '14 at 18:47

1 Answers1

24

You probably have a variable of type NSUInteger, something like

NSUInteger myNumber;

Then you can convert it to a string like this:

NSString *text = [NSString stringWithFormat:@"%li",  myNumber];

A solution that I prefer now is this:

NSString *text = [NSString stringWithFormat:@"%@",  @(myNumber)];   

This helps avoid compile warnings about incorrect number formatting codes (after a long time I still get confused in them).

worldofjr
  • 3,868
  • 8
  • 37
  • 49
TotoroTotoro
  • 17,524
  • 4
  • 45
  • 76
  • I do have an NSUInteger in a variable but the line gives me the error that the "implicit cast of NSUInteger not allowed under ARC." Your solution is what I have found online but it doesn't work for me. – tangobango May 25 '14 at 17:07
  • 2
    Get rid of the parentheses. – rmaddy May 25 '14 at 17:13
  • @rmaddy thanks. I copy-pasted the original code and didn't notice them. – TotoroTotoro May 25 '14 at 17:15
  • @tangobango try now. I've updated the code. – TotoroTotoro May 25 '14 at 17:15
  • @maddy That solved it. Thanks. Adding the parens was something I had found online and didn't remove them after that idea failed. – tangobango May 25 '14 at 17:20
  • Does anyone know whether wrapping the number up in a literal like @(x) has a performance hit or not? – fatuhoku Apr 05 '15 at 22:43
  • @fatuhoku it probably does, since I think it converts the primitive value to an `NSNumber`. But you have to ask yourself if this operation happens often enough to matter. Printing to console is expensive to begin with, and if you write to console a lot, it's a problem, with or without using the `@()` syntax. – TotoroTotoro Apr 07 '15 at 22:49