【问题标题】:how to keep an UIImage from disappearing after an app resumes from a background? (iPad)应用程序从后台恢复后如何防止 UIImage 消失? (iPad)
【发布时间】:2011-06-26 15:12:48
【问题描述】:

我有一个 UIImage* loadedPoofSprite,我像这样初始化它:

NSMutableDictionary* loadedDictionary=[NSDictionary dictionaryWithContentsOfFile:[NSString stringWithFormat:@"%@/%@",Main_Bundle_Path,poofConfigFileName]];
NSString *textureFileName = [[loadedDictionary objectForKey:@"metadata"] valueForKey:@"textureFileName"];
loadedPoofSprite = [UIImage imageNamed:textureFileName]; 

poofImage = [[UIImage imageNamed:textureFileName] CGImage];

从那里我使用我的 poofImage 并且一切似乎都很好,直到我的应用程序从后台恢复。我崩溃了,因为loadedPoofSprite 不见了。我认为避免这种情况的方法是像这样保留loadedPoofSprite:

[loadedPoofSprite autorelease];
loadedPoofSprite = [[UIImage imageNamed:textureFileName] retain]; 

这可行,但有人建议我这样做不是正确的方法,我基本上应该在 applicationWillEnterForeground 中再次加载loadedPoofSprite。我不明白为什么最好加载两次而不是保留它。处理上述问题的正确方法是什么?

谢谢!

【问题讨论】:

    标签: ios background uiimage multitasking retain


    【解决方案1】:

    如果您将loadedPoofSprite 设为保留属性,并将其分配为:

    self.loadedPoofSprite = [UIImage imageNamed:textureFileName];
    

    那么一切都会好起来的。使用

    声明保留属性
    @property (nonatomic,retain) UIImage *loadedPoofSprite;
    

    你需要使用生成一个getter/setter

    @synthesize loadedPoofSprite;
    

    然后在dealloc 例程中,添加self.loadedPoofSprite = nil; 以在需要时释放图像。

    【讨论】:

      【解决方案2】:

      您没有具体说明您对loadedPoofSprite/poofImage 的用途。 可能问题与保留/释放无关:例如,如果您将图像作为子视图添加到另一个视图(通过 UIImageView),则框架会自动保留您的图像,因此不需要自己保留它,并且可能会阻止在系统需要时卸载它。

      确实,您的应用程序在后台运行时可能会受到系统试图恢复内存以使另一个应用程序运行的影响;在这种情况下,您的视图将被释放,可能会被释放,并且在恢复到前台时,您的应用程序将找不到它的视图。因此失败了。

      如果我的推理适用,您将需要检查您的 UIViews 是否存在,并准备好根据需要重新加载/重新创建它们(由有关 didReceiveMemoryWarning/viewWillLoad/viewDidUnload 的文档指定)。

      【讨论】:

        猜你喜欢
        • 2012-11-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-11-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多