NDY
NDY

Reputation: 3557

NSString and isEqualToString with strange output

I got a error in my app and as I tried to fix it I had a really strange behavior when I debugged my method.

Check the following code:(testString is an NSString)

NSLog(@"logging:AAAA%@AAAA",[testObject testString]);

if ([[testObject testString] isEqualToString:@"(null)"]) {
    NSLog(@"yeah im here!");
}

and its printing:

logging:AAAA(null)AAAA

But it never reaches the "yeah im here!". How is that possible?

Upvotes: 2

Views: 274

Answers (6)

prashant
prashant

Reputation: 1920

if ((testObject==nil)||([[testObject testString] isEqualToString:@"(null)"])) {
    NSLog(@"yeah im here!");
}

Upvotes: 0

YuAo
YuAo

Reputation: 1427

NSLog always prints the description of an Object.

In fact it's NS_FORMAT_FUNCTION.

FOUNDATION_EXPORT void NSLog(NSString *format, ...) NS_FORMAT_FUNCTION(1,2);

So:

NSString *stringForNSLog = [NSString stringWithFormat:@"%@",[testObject testString]];

the *stringForNSLog should exactly be "(null)".

But the value of testString is nil.

If you're looking into GNUStep, an open-source implementation of Apple's Cocoa, you'll find something like this:

all the string format things are written in GSFormat.m

and in GSFormat.m

size_t len;
id obj;
NSString *dsc;

obj = args_value[specs[nspecs_done].data_arg].pa_object;

if (!obj) dsc = @"(null)";
else if ([obj respondsToSelector: @selector(descriptionWithLocale:)]) dsc = [obj descriptionWithLocale: locale];
else dsc = [obj description];

http://svn.gna.org/svn/gnustep/libs/base/trunk/Source/NSString.m

http://svn.gna.org/svn/gnustep/libs/base/trunk/Source/GSFormat.m

Upvotes: 2

Bits demystified
Bits demystified

Reputation: 86

Because testString method returns nil and calling a method on nil does nothing.

Upvotes: 1

Resh32
Resh32

Reputation: 6590

Because the testObject is nil itself.

You could test:

if ((testObject==nil)||([[testObject testString] isEqualToString:@"(null)"])) {
    NSLog(@"yeah im here!");
}

Upvotes: 0

highlycaffeinated
highlycaffeinated

Reputation: 19867

NSLog prints the literal (null) if your NSString is nil. Change your test to:

if ([[testObject testString] == nil)

Upvotes: 0

kuba
kuba

Reputation: 7389

The output of testString is nil.

NSLog produces "(null)" when passed a nil object. However calling a method (like isEqualToString) on a nil object evaluates to nil again and thus to false in the "if".

Upvotes: 3

Related Questions