【问题标题】:iPhone convert NSString to NSURL erroriPhone 将 NSString 转换为 NSURL 错误
【发布时间】:2010-07-28 19:49:47
【问题描述】:

我正在尝试将以下 NSString api 调用转换为 NSURL 对象:

http://beta.com/api/token="69439028"

这是我设置的对象。我已经用反斜杠转义了引号:

NSString *theTry=@"http://beta.com/api/token=\"69439028\"";
NSLog(@"theTry=%@",theTry);


NSMutableURLRequest *url = [[NSURL alloc] URLWithString:theTry];
NSLog(@"url=%@",url);

每次我运行这个,我都会收到这个错误:

2010-07-28 12:46:09.668 RF[10980:207] -[NSURL URLWithString:]: unrecognized selector sent to instance 0x5c53fc0
2010-07-28 12:46:09.737 RF[10980:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSURL URLWithString:]: unrecognized selector sent to instance 0x5c53fc0'

有人可以告诉我如何正确地将这个字符串转换为 NSURL 吗?

【问题讨论】:

    标签: iphone objective-c


    【解决方案1】:

    您正在声明一个 NSMutableURLRequest 类型的变量并使用 NSURL 初始化函数(有点)。

    NSMutableURLRequest *url = [[NSURL alloc] URLWithString:theTry];
    

    试试

    NSURL *url = [[NSURL alloc] initWithString:theTry];
    

    请注意,我已经有一段时间没有进行任何 iPhone 开发了,但我认为这看起来很准确。

    【讨论】:

    • 或者,你可以通过 NSURL * url = [NSURL URLWithString:theTry]; 获得一个自动释放的对象;
    • @Tom:我试过“NSURL *url = [NSURL URLWithString:theTry]”,但它一直返回一个空对象。
    • @Dutchie432 & Dave:我也试过“NSURL *url = [[NSURL alloc] initWithString:theTry]”,它也给了我一个空对象
    • 根据documentation,返回 nil 的 URLWithString 意味着您的字符串格式错误。双引号 (") 很可能会弄乱您的字符串,应该转义。
    • 对 URL 进行转义(编码)不会添加反斜杠。见 URL 编码:tikirobot.net/wp/2007/01/27/url-encode-in-cocoa
    【解决方案2】:

    首先,你必须在这一行得到一个编译错误: NSMutableURLRequest *url = [[NSURL alloc] URLWithString:theTry]; 但我很惊讶你是如何编译它的......

    你做错了什么是你在类 NSURL 的实例上调用一个类方法。

    URLWithString:是NSURL类的一个类方法,所以你必须把它当作:

    NSMutableURLRequest *url = [NSURL URLWithString:url];
    

    initWithString:是一个实例方法,所以你必须把它当作:

    NSMutableURLRequest *url = [[NSURL alloc] initWithString:url];
    

    【讨论】:

      猜你喜欢
      • 2011-12-26
      • 2016-04-07
      • 2016-11-15
      • 2012-02-10
      • 1970-01-01
      • 2012-04-05
      • 2014-10-25
      • 1970-01-01
      • 2016-07-28
      相关资源
      最近更新 更多