为什么我的jpg文件的绝对路径不起作用

时间:2012-08-10 07:36:56

标签: xcode path

我查了几个类似的问题,但没有找到我的问题的答案。

问题的第一部分是如何编写文件的相对路径。我没有得到这项工作,但让我暂时移动第二部分。由于我无法获得相对路径的工作,所以我尝试了绝对路径。这是我使用的代码:

NSString *path = [NSString stringWithFormat:@"/Users/my.name/Documents/TestFour/TestFour/Library/file%d.txt", i]; //where i is 1 or 2
//NSString *path = [NSString stringWithFormat:@"./TestFour/Library/file%d.txt", i]; //this relative path didn't work, although TestFour.xcodeproj and TestFour are in the same directory and TestFour has child directory Library and xxx.h and xxx.m files
NSString *spath = [path stringByStandardizingPath];
NSLog(@"file is %@", spath);
if (spath) {
    NSString *myText = [NSString stringWithContentsOfFile:spath encoding:NSUTF8StringEncoding error:nil];
    //continue, and I got myText ....

现在我有一个jpg文件,比如myPic.jpg,与上面的file1.txt在同一个目录中,即在Library文件夹中。我想将这个图像加载到UIImageView中,这是我的代码,但它失败了。

NSString *path = @"/Users/my.name/Documents/TestFour/TestFour/Library/myPic.jpg";
NSString *spath = [path stringByStandardizingPath];

[self._bgView setImage:[UIImage imageNamed:spath]];

但是,我尝试了一个基于Web的图像,BTW来自另一个相关的线程,它工作:     [self._bgView setImage:[[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@“http://farm4.static.flickr.com/3092/2915896504_a88b69c9de.jpg”]]];

所以我很困惑为什么我能阅读the_same_folder_file1.txt但却没有加载the_same_folder_myPic.jpg

回到第一部分,为什么我的相对路径不起作用?不确定这是否相关,当我将此jpg和其他jpg拖入项目时,我被问及并选择了默认设置(Group或类似的东西)。我不知道是否需要将这个jpg拖到项目中,但是在拖动之前和之后代码都无法正常工作。

1 个答案:

答案 0 :(得分:0)

[UIImage imageNamed]将从应用包中加载具有给定名称的文件;你想要的是[UIImage imageWithContentsOfFile]reference)。

此外,您需要了解相对文件路径是基于进程的当前工作目录而工作的。你知道那是什么吗?如果没有,那么您可以使用以下内容进行记录:

char cwd[1024];
getcwd(cwd, sizeof(cwd));
NSLog(@"cwd='%s'", cwd);

(您可能需要#import <unistd.h>)。

或许这可以帮助您解决相对路径问题。