我在Xcode 4.5.2中得到了“弃用”警告

时间:2012-11-19 17:56:52

标签: iphone ios xcode

NSURL *jsonURL = [NSURL URLWithString:@"http://ambiguous.dubbelzinnig.com/index.php?    get_cat=1"];

NSString *jsonData = [[NSString alloc] initWithContentsOfURL:jsonURL];

if (jsonData == nil) {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Webservice Down" message:@"The webservice you are accessing is down. Please try again later."  delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [alert show];
    [alert release];
}
else {...

似乎需要更改initWithContentsOfURL,但我已经尝试了它在开发人员指南中所说的内容,但我无法让它工作......有人可以修复此代码吗?

非常感谢!

2 个答案:

答案 0 :(得分:2)

改为使用initWithContentsOfURL:encoding:error:initWithContentsOfURL:usedEncoding:error:

例如:

NSURL *jsonURL = [NSURL URLWithString:@"http://ambiguous.dubbelzinnig.com/index.php?get_cat=1"];
NSError *error = nil;
NSString *jsonData = [[NSString alloc] initWithContentsOfURL:jsonURL encoding:NSUTF8StringEncoding error:&error];
if( error == nil ) {
    // Parse jsonData
} else {
    // There was a problem
}

您需要将编码值替换为实际编码类型的枚举。 NSString类中有许多用于此目的的枚举...请参阅:https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html中的“字符串编码”部分

答案 1 :(得分:1)

为什么不查看documentation

  

<强> initWithContentsOfURL:

     

通过读取数据初始化接收器,即新分配的NSString对象   从给定URL指定的位置。 (在OS X v10.4中不推荐使用    initWithContentsOfURL:encoding:error:或    initWithContentsOfURL:usedEncoding:error:代替。)