【问题标题】:iPhone: setting an image programmatically from the Documents folderiPhone:以编程方式从 Documents 文件夹设置图像
【发布时间】:2011-08-31 10:47:12
【问题描述】:

您好,我的一个视图中有一个名为 promoBanner 的 UIImageView 插座。我正在尝试编写以编程方式设置此插座的代码。基本上,该应用程序在 NSBundle 中附带了一个图像。但我想确保它从文档文件夹中获取图像。我想这样做是因为将来会有不同的“促销”,并且应用程序应该在“promoBanner”图像视图中显示正确的图像。这是我编写的代码,但我不确定它为什么不起作用。有人可以给我一个想法:

- (void)viewDidLoad
{
    [super viewDidLoad];
    //==========================================================================
    NSError *error;
    NSString *errorDesc = nil;
    NSPropertyListFormat format;
    NSData *promoImg;
    NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *promoImgDocPath = [rootPath stringByAppendingPathComponent:@"promoBanner.png"];
    NSFileManager *fileManager = [NSFileManager defaultManager];

    if (![fileManager fileExistsAtPath:promoImgDocPath]) 
       {
        NSString *plistBundlePath = [[NSBundle mainBundle] pathForResource:@"promoBanner" ofType:@"png"];
        [fileManager copyItemAtPath:plistBundlePath toPath:promoImgDocPath error:&error]; 
        if(![fileManager fileExistsAtPath:promoImgDocPath])
           {
            NSLog(@"The copy function did not work, file was not copied from bundle to documents folder");
           }
       }

    self.promoBanner.image =[UIImage imageWithContentsOfFile:promoImgDocPath];

    if (!self.promoBanner.image) 
       {
        NSLog(@"Error setting image: %@, format: %d", errorDesc, format);
       }

非常感谢 错误:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSFileManager copyItemAtPath:toPath:error:]: source path is nil'

* 首次抛出时调用堆栈:

CoreFoundation 0x3759dc7b __exceptionPreprocess + 114

libobjc.A.dylib 0x32d9bee8 objc_exception_throw + 40

CoreFoundation 0x3759dac3 +[NSException raise:format:arguments:] + 70

CoreFoundation 0x3759daf7 +[NSException raise:format:] + 30

基础 0x351a8653 -[NSFileManager copyItemAtPath:toPath:error:] + 90

餐厅 0x000068c3 -[AboutViewController viewDidLoad] + 286

UIKit 0x35926e60 -[UIViewController 视图] + 160

【问题讨论】:

  • 您遇到的错误是什么?
  • @Deepak。我已编辑我的帖子以显示错误

标签: iphone uiimageview


【解决方案1】:

如果 promoBanner.png 不是我的捆绑包中的文件,我会收到您的错误。但是,如果我将文件添加到项目中,代码将编译。

您确定已将 promoBanner.png 添加到您的项目中吗(通过将其拖入 XCode 或使用“文件 -> 将文件添加到”

【讨论】:

    【解决方案2】:
    [[NSBundle mainBundle] pathForResource:@"promoBanner" ofType:@"png"];
    

    返回零。如果该文件不在您的工作区中,请添加它。如果是,请检查以确保您实际上已将映像包含在构建中。在 Xcode 4 中:

    • 在文件浏览器中选择根项目项。
    • 从“目标”列表中选择合适的目标
    • 选择“构建阶段”标签
    • 展开“复制捆绑资源”项并查找您的图像文件。

    【讨论】:

      猜你喜欢
      • 2011-04-13
      • 1970-01-01
      • 1970-01-01
      • 2017-02-26
      • 2011-04-06
      • 1970-01-01
      • 2017-01-24
      • 2013-09-28
      • 1970-01-01
      相关资源
      最近更新 更多