NSURL 对于单字符非 ASCII 字符串不返回 nil

发布于 2025-01-02 16:33:31 字数 395 浏览 5 评论 0原文

我一直在使用 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 技术交流群。

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

发布评论

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

评论(1

冷默言语 2025-01-09 16:33:31

我无法解释您在上面看到的行为,但是,如果您想要做的只是确定 URL 字符串是否包含任何非 ASCII 字符,您可以使用以下代码来实现此目的:

NSString *testURLString = @"http://www.googleあか.com";

NSCharacterSet* ascii = [NSCharacterSet characterSetWithRange: NSMakeRange(0, 128)];
NSCharacterSet* nonAscii = [ascii invertedSet];

if ([testURLString rangeOfCharacterFromSet:nonAscii].location != NSNotFound) {
    NSLog(@"This string contains non-ASCII characters");
}

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:

NSString *testURLString = @"http://www.googleあか.com";

NSCharacterSet* ascii = [NSCharacterSet characterSetWithRange: NSMakeRange(0, 128)];
NSCharacterSet* nonAscii = [ascii invertedSet];

if ([testURLString rangeOfCharacterFromSet:nonAscii].location != NSNotFound) {
    NSLog(@"This string contains non-ASCII characters");
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文