【问题标题】:What happens to array values after replacing them in Swift?在 Swift 中替换数组值后会发生什么?
【发布时间】:2015-12-14 09:42:20
【问题描述】:

我想知道,当我用另一个数组替换它们时,数组(任何类型)的值是否会自动取消。例如 UIImage-Array 的第一个值被另一个图像替换。数组先前包含的第一个图像会发生什么?是仅删除了引用还是从 RAM 中删除了图像本身?

感谢您的回答!

【问题讨论】:

    标签: ios arrays swift memory


    【解决方案1】:

    只有在没有更多引用时才会发布该图像。

    查看Automatic Reference Counting 了解更多信息。

    【讨论】:

      【解决方案2】:

      这里将使用 ARC 的概念。 第一个图像也是一个 UIImage 实例,当你用第二个 UIImage 对象替换第一个 UIImage 对象时,对第一个对象的强引用被删除。 案例 1:(现在,我假设您没有在任何其他行中使用第一个 UIImage 实例或分配给任何其他变量。) 因为,该对象没有对它的任何强引用。当您将其替换为第二个图像的对象时,ARC 会自动将其从内存中删除。

      CASE 2:但是如果你也将它分配给下一个变量,那么它不会被删除。 让我用例子来演示一下:


      案例 1:

      var images = [UIImage]()
      images.append(UIImage(named: "elcapitan"))
      //now this first image is stored in index number 0 of the array
      //images[0] gives you access to this first image in this case
      
      //now i will replace the first image
      images[0] = UIImage(named: "yosemite")
      

      在这种情况下,ARC 会自动删除第一个图像实例,因为它没有从任何地方强引用


      案例 2:

      var images = [UIImage]()
      var firstImage = UIImage(named: "elcapitan")
      images.append(firstImage)
      //now this first image is stored in index number 0 of the array
      //images[0] gives you access to this first image in this case
      
      //now i will replace the first image
      images[0] = UIImage(named: "yosemite")
      

      在这种情况下,ARC 无法删除第一个图像实例,因为它仍然被变量 firstImage 强引用,尽管您已在数组中替换。只有在将下一个图像分配给 firstImage 变量后,该实例才会被删除。即仅当您这样做时: firstImage = UIImage(name: "Windows")

      希望你得到你的答案:)

      【讨论】:

        【解决方案3】:

        Swift 使用自动引用计数 (ARC)。而且你必须记住swift中类和结构之间的区别。

        来自 Apple 的文档:

        引用计数仅适用于类的实例。结构和枚举是值类型,而不是引用类型,并且不通过引用存储和传递。

        简而言之,ARC 会跟踪有多少常量、变量和属性正在引用(强引用)类的实例。如果没有引用,ARC 会释放实例并释放内存。

        class Person {
           var name: String
        
           init(name: String) {
             self.name = name
           }
        }
        
        var steve: Person? = Person(name: "Steve") // Increasing ref counter -> 1
        var sameSteve: Person? = steve // Increasing ref counter -> 2
        
        steve = nil // Decreasing ref counter -> 1
        
        print(sameSteve?.name) // prints "Steve"
        
        sameSteve = nil // Decreasing ref counter -> 1
        
        print(sameSteve?.name) // prints nil because it was deallocated
        

        因此,由于UIImage 是一种引用类型,如果从数组中删除或替换,ARC 将减少其引用计数器。如果没有其他变量、常量或属性持有它,图像将被释放。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-10-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-04-08
          • 2017-02-18
          相关资源
          最近更新 更多