UTF8字符串问题

发布于 2024-12-04 06:02:24 字数 405 浏览 6 评论 0原文

我遇到了这个 UTF8String 的奇怪问题:

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

我的问题是:

  1. 为什么我必须进行此转换才能记录 parentMode

  2. 日志正在打印Sleep。那么,如果无论如何完成的话,它是如何完成的呢?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

岁月染过的梦 2024-12-11 06:02:24

您无法使用普通的关系运算符来比较字符串,您必须使用:

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

但是,在使用该方法之前,您可能需要检查 parentMode 是否不 nil。您不需要使用 UTF8String 方法,可以直接使用 %@ 格式说明符来记录字符串。如果这不起作用,那么您在提供的代码中省略了一些非常重要的内容。

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.

半夏半凉 2024-12-11 06:02:24

要记录字符串,您可以编写:

 NSLog(@"%@", parentMode);

使用 %@ 占位符,无需将其转换回 UTF-8。

这可能也解释了为什么 if 语句有效。

更新:

您应该将字符串与isEqualToString:进行比较

[parentMode isEqualToString: @"Sleep"]

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"]
水水月牙 2024-12-11 06:02:24

如果您要比较整数,那么您必须使用帖子中使用的语法。但是当您比较字符串时,请使用此语法。

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

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);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文