XCode:将应用程序转换为Xcode5后,NSURL变量在运行时为零:它在之前的版本4.5中有效

时间:2013-10-02 08:37:36

标签: xcode5 nsurl

以下代码在Xcode 4.5中工作:在带有图像的ViewController中,从URL加载文件并附带图像描述:文件名已本地化,以便根据需要加载正确的文件意大利语或英语设置。


NSString *stringaLocalizzata = (NSString *) NSLocalizedString(@"DISCO1_PAGE",nil);
/* Localized file name that contains the object description in english or italian
/* values: 1_locale_en.txt for english
/*         1_locale.txt for italian


NSString *bioLocaleUrl =[[[@"http://" stringByAppendingString:aConstrants.disco_url]stringByAppendingString:aConstrants.doc_dir] //stringByAppendingString:stringaLocalizzata];
       stringByAppendingString:stringaLocalizzata];

NSURL *bioLocaleUrlVersion = [NSURL URLWithString: bioLocaleUrl];
NSError *error = nil;
NSString *bioLocaleWebVersion = [NSString stringWithContentsOfURL:bioLocaleUrlVersion encoding:1 error:&error];

 _bioLocale.text=bioLocaleWebVersion;

使用Xcode5它不起作用:在开始时我认为这是一个令人着迷的问题,但真正的问题是 NSURL * bioLocaleUrlVersion = [NSURL URLWithString:bioLocaleUrl]; 结果在运行时没有。

如果我以这种方式更改代码:


NSString *bioLocaleUrl =[[[@"http://" stringByAppendingString:aConstrants.disco_url]stringByAppendingString:aConstrants.doc_dir] //stringByAppendingString:stringaLocalizzata];
       stringByAppendingString:@"1_locale_en.txt"];

然后* bioLocaleUrlVersion将不会是零并且一切正常。 当然我可以用不同的方式处理这个问题,但我想了解哪个是问题所在。 感谢。

1 个答案:

答案 0 :(得分:1)

尝试使用无效的URL字符串创建NSURL对象将返回nil。在您的stringByAppendingString:次调用中出现问题导致URL字符串无效(请参阅NSURL类引用的顶部,以获取有效内容的完整详细信息。

在不知道bioLocaleUrl的价值的情况下,我无法提供更具体的建议。

我强烈建议使用操作系统更合适的例程。从iOS 7开始,NSURLComponents是一个不错的选择:

NSURLComponents *components = [[NSURLComponents alloc] init];
components.scheme = @"http";
components.host = aConstrants.disco_url;
components.path = [aConstrants.doc_dir stringByAppendingPathComponent:stringaLocalizzata];

(基于你在问题中的代码,这似乎是合理的)

对于较旧的操作系统版本,我建议-[NSURL URLByAppendingPathComponent:]是您的朋友。