1

我想从位于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 Simulator/5.0/Applications/6842528E-9629-4DE7-96C1-A46AEB8A8EE0/Library/Thapa

它应该是:

getImagePath 的打印说明:

/Users/Admin/Library/Application Support/iPhone Simulator/5.0/Applications/6842528E-9629-4DE7-96C1-A46AEB8A8EE0/Library/Thapa/images47.png

如何实现这一点不知道,我尝试的是上面的。

提前致谢

4

2 回答 2

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

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

编写的代码更多,但阅读和遵循要容易得多。通过走这条路线,您也许可以找出问题所在。

于 2012-10-31T12:41:21.750 回答
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);
于 2012-10-31T12:41:15.440 回答