Reputation: 21
I have a person object of class Person with property is address, age. When I check properties, I print address on screen with:
NSLog(@"Add: %@, length: %i", person.address, [person.address length]);
The result is: Add: nil, length: 6
Can you explain for me why the string is null but its length shows as 6?
Thanks.
Upvotes: 2
Views: 210
Reputation: 11
You are probably getting the string value of "(null)" in the field somehow, which is 6 characters long.
Upvotes: 1
Reputation: 52565
The answer you're probably looking for is: you're using the wrong string format specifier. I'm not sure what %i
is; %d
is for integers and %u
for unsigned, so you need:
NSLog(@"Add: %@, lenght: %u", person.address, [person.address length]);
But... the length is possibly not returning what you think it is.
If person.address
is nil
, then sending the message length
to it won't return the length (what is the length of "nothing"?). As it happens, the Objective C runtime will return zero so your example "works" but is arguably not correct.
Upvotes: 0
Reputation: 4520
What type is address? NSString I assume? use %d or %lu for length (and cast to unsigned long if using %lu) instead of %i - that should give correct result.
Length gives a NSUInteger as a result, correct string format specifier would hence be %lu although %d should also work (thinking of it, I always use %d). I never as %i...
NSLog(@"%lu", (unsigned long)string.length)
Look at the format specifies:
Upvotes: 0