NSURL 对于单字符非 ASCII 字符串不返回 nil
我一直在使用 NSURL 进行简单的 URL 验证,主要是为了清除非 ASCII 特殊字符,这些字符在我的特定应用程序中是不需要的。我将 URL 作为 NSString 的输入,然后尝试使用 URLWithString 创建 NSURL。如果返回 nil,应用程序会显示一条错误消息。
例如,如果我输入“あか”作为输入(即两个日语字符),则 NSURL 为零。这已经按预期进行了。然而我最近注意到,输入一个仅包含一个非 ASCII 字符的字符串,NSURL 会处理它并返回一个 URL 编码值。因此,如果我输入“あ”作为输入,则生成的 NSURL 不为零。绝对字符串值为“%E3%81%82”。
我想知道这是否是 NSURL 中的错误,或者是某种我不理解的漏洞。
我使用的是 Xcode 3.2.5 和 iOS 4.2 SDK。
I have been using NSURL to do a simple URL validation, mostly to weed out non-ascii special characters, which I do not want in my particular application. I take a URL as input into an NSString, then try to create an NSURL using URLWithString. If this returns nil, the app presents an error message.
For example if I enter "あか" as input (that is two Japanese characters), then the NSURL is nil. This has been working as expected. However I recently noticed that entering a string that is contains only one single non-ASCII character, NSURL processes it and returns a URL-encoded value. So if I enter "あ" as input, the resulting NSURL is NOT nil. The absoluteString value is "%E3%81%82".
I'm wondering if this is a bug in NSURL, or some kind of loophole that I'm not understanding.
I'm using Xcode 3.2.5, and the iOS 4.2 SDK.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我无法解释您在上面看到的行为,但是,如果您想要做的只是确定 URL 字符串是否包含任何非 ASCII 字符,您可以使用以下代码来实现此目的:
I can't explain the behavior you are seeing above, however, if all you are trying to do is determine whether a URL string contains any non-ASCII characters, you could achieve this with the following code: