initWithContentsOfURL suddenly gives a “deprecated” error
-
15-04-2021 - |
Pergunta
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.
}
Solução
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.
}
Outras dicas
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;
That method has been deprecated and replaced by
initWithContentsOfURL:enconding:error
or
initWithContentsOfURL:usedEnconding:error
Cheers
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.
}
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.