0
const char *string ="Hi there,this is a C string";
NSData *data=[NSData dataWithBytes:string 
                            length:strlen(string)+1];
NSLog(@"data is %@",data);
NSLog(@"%lu byte string is '%s'",[data length],[data bytes]);

This can be implied successfully. If the last sentence is:

NSLog(@"%d byte string is '%s'",[data length],[data bytes]);

it will warn that conversion specifies type 'int' but argument has typed 'NSUInteger' (aka'usigned long')

Why %d can't?

pasawaya
  • 11,515
  • 7
  • 53
  • 92
Lucas Huang
  • 3,998
  • 3
  • 20
  • 29

2 Answers2

2

NSUInteger is basically an unsigned long, so use %lu instead.

TheAmateurProgrammer
  • 9,252
  • 8
  • 52
  • 71
  • but the question is y the '%d' can't .The textbook wrote it. – Lucas Huang Jul 15 '12 at 03:15
  • 1
    I don't know what textbook you're reading, but in ObjC you need to pass the correct "long/short" and "signed/unsigned" in the format specifier. %lu is correct (long unsigned). %d (short, signed) is not. – Rob Napier Jul 15 '12 at 03:43
  • thank you for you answer. Perhaps the textbook has to be improved or the translators.Thank you! – Lucas Huang Jul 15 '12 at 11:18
0

%d means 'int'. NSUInteger is not an 'int', so %d won't work. You have to match format specifiers with the type. If you specify the wrong type, your program can crash or more likely, it'll print garbage.

Graham Perks
  • 23,007
  • 8
  • 61
  • 83
  • %d is for ints. %f for doubles. All the specifiers are documented here: https://developer.apple.com/library/mac/ipad/#documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html – Graham Perks Jul 15 '12 at 14:03