objective-c stringByAddingPercentEscapesUsingEncoding 在 9.0 中已弃用。如何执行此操作?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34015750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 21:36:58  来源:igfitidea点击:

stringByAddingPercentEscapesUsingEncoding was deprecated in 9.0 .How to do this?

objective-c

提问by Just Lai

I'm a junior developer, and I got a code for this:

我是一名初级开发人员,我得到了一个代码:

(NSString *)encodedStringFromObject:(id)object {
    return [[object description] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];    
}

But in 9.0 have to use stringByAddingPercentEncodingWithAllowedCharacters.

但是在 9.0 中必须使用stringByAddingPercentEncodingWithAllowedCharacters.

How Could I transfer this code ? I need help, Thanks!

我怎么能转移这个代码?我需要帮助,谢谢!

回答by sage444

If you want just fast example look at this code:

如果您只想快速示例,请查看此代码:

NSString * encodedString = [@"string to encode" stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];

Also check List of predefined characters sets

还要检查预定义字符集列表

If you want explanation read the documents or at least this topic: How to encode a URL in Swift

如果你想解释阅读文档或至少这个主题:How to encode a URL in Swift

回答by Ishwar Hingu

URL = [[NSString stringWithFormat:@"%@XYZ",API_PATH]stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

回答by gnasher729

You'd read the spec for both functions. Then you would find out for what purpose characters are replaced with escape sequences. From there you would find out the set of allowed characters, which must be documented somewhere.

您已经阅读了这两个函数的规范。然后你会发现用转义序列替换字符的目的是什么。从那里你会发现允许的字符集,必须在某处记录。

That's an essential part of changing from junior to normal to senior developer: Find out exactly what your code is supposed to do, which shouldbe defined somewhere, and then make it do what it should do.

这是从初级开发人员到普通开发人员再到高级开发人员的重要组成部分:确切地找出您的代码应该做什么,应该在某处定义哪些,然后让它做它应该做的事情。

stringByAddingPercentEscapesUsingEncoding is probably deprecated because it doesn't know which characters are allowed and sometimes gives the wrong results.

stringByAddingPercentEscapesUsingEncoding 可能已被弃用,因为它不知道允许使用哪些字符,有时会给出错误的结果。

回答by Amit Hooda

You can use stringByRemovingPercentEncoding instead of stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding

您可以使用 stringByRemovingPercentEncoding 而不是 stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding

[@"string" stringByRemovingPercentEncoding];

[@"string" stringByRemovingPercentEncoding];

回答by Pankaj Gaikar

Here is solution to do in Swift

这是在 Swift 中要做的解决方案

var encodedString = "Hello, playground".addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)