没有获得NSLibraryDirectory的完整路径

时间:2012-10-31 12:33:41

标签: iphone directory

我想从位于NSLibraryDirectory

的文件夹中获取图片
 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask, YES);
 NSString *documentsDirectory = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:str]];

 NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent: [@"images" stringByAppendingFormat:@"%d",[[NSUserDefaults standardUserDefaults] integerForKey:@"HighScore"]] stringByAppendingFormat:@".png"];
 img = [UIImage imageWithContentsOfFile:getImagePath];
 NSLog(@"img:%@", img);

这是我正在使用的代码

打印getImagePath的描述:

  

/ Users / Admin / Library / Application Support / iPhone   模拟器/ 5.0 /应用/ 6842528E-9629-4DE7-96C1-A46AEB8A8EE0 /库/塔帕

应该是:

打印getImagePath的描述:

  

/ Users / Admin / Library / Application Support / iPhone   模拟器/ 5.0 /应用/ 6842528E-9629-4DE7-96C1-A46AEB8A8EE0 /库/塔帕/ images47.png

如何实现这一点不知道,我在上面尝试了什么。

提前致谢

2 个答案:

答案 0 :(得分:2)

首先,你在一行代码中做了太多的事情。编写代码的最佳实践是保持简单(因此您的代码对于您和其他任何查看代码的人都是可读的。)

当我看到这一行时:

NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent: [@"images" stringByAppendingFormat:@"%d",[[NSUserDefaults standardUserDefaults] integerForKey:@"HighScore"]] stringByAppendingFormat:@".png"];

那里发生的太多了!

为什么不这样做:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,     NSUserDomainMask, YES);
if(paths)
{
    NSString *documentsDirectory = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:str]];
    if(documentsDirectory)
    {
        NSInteger highScoreNumber = [[NSUserDefault standardUserDefaults] integerForKey: @"HighScore"];
        NSString * numberGraphicFilename = [NSString stringWithFormat: @"images%d.png", highScoreNumber ];
        if(numberGraphicFilename)
        {
            NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent: numberGraphicFilename];
            if(getImagePath)
            {
                img = [UIImage imageWithContentsOfFile:getImagePath];
            }
        }
    }
}

奖励:这也为您的代码引入了错误检查/处理的概念。

这是更多的代码编写,但它更容易阅读和遵循。而且你可以通过走这条路来找出问题所在。

答案 1 :(得分:0)

getImagePath 更改为

NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent: [@"YourSubFolderName/images" stringByAppendingFormat:@"%d",[[NSUserDefaults standardUserDefaults] integerForKey:@"HighScore"]] stringByAppendingFormat:@".png"];

所以您的代码将如下所示

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,     NSUserDomainMask, YES);
NSString *documentsDirectory= [paths objectAtIndex:0];

NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent: [@"YourSubFolderName/images" stringByAppendingFormat:@"%d",[[NSUserDefaults standardUserDefaults] integerForKey:@"HighScore"]] stringByAppendingFormat:@".png"];
img = [UIImage imageWithContentsOfFile:getImagePath];
NSLog(@"img:%@", img);