由于内存问题,iOS应用程序在加载UIImage时崩溃

问题描述:

我的问题与

My question is extremely similar to iOS Application Crash while UIImage loading (virtual memory not cleaning up) in that I have an array of objects, and each object has a picture as one of it's variables. The answer in the above post seems to be that the objects remain even after they were removed from the array. However I cannot seem to figure out exactly what he did to fix this issue. I am using Swift, and have no experience in Objective-C.

有人可以告诉我他为解决此问题做了什么吗?答案中他的示例代码对我来说毫无意义.

这是我的课程,其中包括image属性:

Here is my class, which includes the image property:

open class Cards {
    var name = ""
    var image : UIImage!
    var manaCost = 0
    var rarity = ""
    var whichClass = ""
    var cardText = ""
    var tribe = ""
    var cardType = "" //Minion or Spell
    var set = ""


    init(name : String,  image : UIImage!,  manaCost : Int, rarity : String, whichClass : String, cardType : String, tribe : String, cardText : String, set : String)
    {
        self.name = name
        self.image = image
        self.manaCost = manaCost
        self.rarity = rarity
        self.whichClass = whichClass
        self.cardType = cardType
        self.tribe = tribe
        self.cardText = cardText
        self.set = set
    }

    deinit {
         print("deinit " + name);
    }

}

对象的初始化看起来像这样:

The initialization of the objects looks a little something like this:

var ArgeonHighmayne = Cards(name: "Argeon Highmayne", image :  UIImage( named  : "ArgeonHighmayne")!, manaCost : 0, rarity : "Basic", whichClass : "Lyonar", cardType : "General", tribe : "None", cardText : "Bloodborn Spell: Give a minion nearby your general +2 Attack.", set : "Core")

以及放置这些对象的数组如下:

and the arrays that these objects are placed in look like this:

public var newestCards = [DayWatcher, NightWatcher, DustWailer, QuartermasterGauj]

我试图通过简单地在声明之前添加弱"并添加所有!"来将对象本身变成弱引用.和 "?" Xcode需要我添加,但这只是导致图像没有出现在我的收藏夹视图中. 我还尝试在类声明本身中添加弱",如下所示:

I have attempted to turn the objects themselves into weak references by simply adding "weak" before the declaration and adding all the "!" and "?" that Xcode required me to add, but this just resulted in the images not appearing in my collection view. I also tried adding "weak" in the class declaration itself like so:

weak var image : UIImage!

但这也导致图像根本不显示. 预先感谢您的帮助.

But this also resulted in the images simply not showing up. Thanks in advance for any help.

原来是崩溃的,因为图像是数组的一部分.与其将UIImage放在类中,不如将图像的名称放在那里,然后在collectionView方法中对该名称调用UIImage.

Turns out it was crashing because the images were part of the array. Instead of putting a UIImage within the class, it is better to put the image's name there, and then call UIImage on that name in the collectionView method.