Search code examples
objective-ccocoanslog

UTF8String problem


I am facing a strange problem with this UTF8String:

parentMode = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
…
if(parentMode != @"Sleep")
{   
    NSLog(@"%s", [parentMode UTF8String]);      
}

My questions are:

  1. Why do I have to do this conversion in order to log parentMode?

  2. The log is printing Sleep. So how is that if is done anyway?


Solution

  • You can't compare strings using the normal relational operators, you must use:

    if (![parentMode isEqualToString:@"Sleep"])
    {
        NSLog (@"%@", parentMode);
    }
    

    You may want to check that parentMode is not nil before using that method, however. You don't need to use the UTF8String method, you can log the string directly using the %@ format specifier. If this is not working, then there is something very important that you are omitting from the code you provided.