开发者

UTF8String problem

开发者 https://www.devze.com 2023-04-04 17:57 出处:网络
I am facing a strange problem with this UTF8String: parentMode = [NSString stringWithContentsOfF开发者_JS百科ile:filePath encoding:NSUTF8StringEncoding error:nil];

I am facing a strange problem with this UTF8String:

parentMode = [NSString stringWithContentsOfF开发者_JS百科ile: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?


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.


To log the string, you can write:

 NSLog(@"%@", parentMode);

Using the %@ placeholder, there's not need to convert it back to UTF-8.

This probably also explains why the if statement works.

Update:

You should compare string with isEqualToString:

[parentMode isEqualToString: @"Sleep"]


If you are comparing the integers then you have to use the syntax whatever you have used in the post.But when you compare the strings use this.

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

精彩评论

暂无评论...
验证码 换一张
取 消