initWithContentsOfURL suddenly gives a "deprecated" error

6.3k views Asked by At

I just opened my project in the new XCode 4.2 for the first time and I'm suddenly getting a whole slew of these warnings: 'initWithContentsOfURL:' is deprecated

Here's the code - anyone know what needs to be fixed here? (it was working perfectly fine in XCode 4.0)

- (void)viewDidLoad
{

    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"TermsConditions" withExtension:@"html"];
    NSString *myHtml = [[NSString alloc] initWithContentsOfURL:modelURL];
    [self.TermsWebView loadHTMLString:myHtml baseURL:modelURL];
    [myHtml release];
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}
5

There are 5 answers

4
dtuckernet On BEST ANSWER

You need to use the method initWithContentsOfURL:usedEncoding:error:

- (void)viewDidLoad
{ 

    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"TermsConditions" withExtension:@"html"];

    NSStringEncoding *encoding;
    NSError *error;

    NSString *myHtml = [[NSString alloc] initWithContentsOfURL:modelURL usedEncoding:&encoding error:&error];
    [self.TermsWebView loadHTMLString:myHtml baseURL:modelURL];
    [myHtml release];
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}
1
Caleb On

When you get a message that a given method is deprecated, check the documentation for information. In this case, you'll find that -initWithContentsOfURL: is no longer listed on the NSString reference page.

Another useful resource is the header file for the class in question. If you check NSString.h, you'll find:

- (id)initWithContentsOfURL:(NSURL *)url DEPRECATED_IN_MAC_OS_X_VERSION_10_4_AND_LATER;
0
AMAN77 On

Try this out it seems to be error free

- (void)viewDidLoad

{

NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"TermsConditions" withExtension:@"html"];

NSStringEncoding *encoding = NULL;
NSError *error;

NSString *myHtml = [[NSString alloc] initWithContentsOfURL:modelURL usedEncoding:encoding error:&error];
[self.TermsWebView loadHTMLString:myHtml baseURL:modelURL];
[myHtml release];
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.

}

0
Vishnu Nair On

This seems to be the correct code:

NSStringEncoding *encoding = NULL; NSString *jsonReturn = [[NSString alloc]initWithContentsOfURL:url encoding:*encoding error:NULL];

The warnings will be eliminated only if , 1.you initialise encoding to NULL. 2.Put a * before encoding.

0
bitoiu On

That method has been deprecated and replaced by

initWithContentsOfURL:enconding:error

or

initWithContentsOfURL:usedEnconding:error

Cheers