【问题标题】:why my absolute path for jpg file doesn't work为什么我的 jpg 文件的绝对路径不起作用
【发布时间】:2012-08-10 07:36:56
【问题描述】:

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

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

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]];

但是,我尝试了一个基于网络的图像,顺便说一句,它来自另一个相关线程,并且它有效: [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 拖到项目中,但是代码在拖之前和之后都不起作用。

【问题讨论】:

    标签: xcode path


    【解决方案1】:

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

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

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

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

    也许这会帮助您解决相对路径问题。

    【讨论】:

    • 好奇心让我检查getcwd() 是否可用.. 它是!但是它只返回/
    • @JamesWebster 是来自沙盒应用程序吗?
    • @JamesWebster 嗯,我对沙盒应用不太熟悉,但这肯定会影响相对路径(我猜它们会变成绝对路径……)
    • imageWithContentOfFile 确实适用于我的 JPG 绝对路径!谢谢。现在需要看一下相对路径。
    猜你喜欢
    • 2022-01-07
    • 2011-05-26
    • 2013-07-06
    • 1970-01-01
    • 1970-01-01
    • 2018-02-18
    • 2014-11-20
    • 2023-03-24
    • 2016-12-17
    相关资源
    最近更新 更多