【问题标题】:Copy a static variable with Swift使用 Swift 复制静态变量
【发布时间】:2016-09-13 11:33:40
【问题描述】:

我使用此代码来调整集合视图的模型。问题是当我修改 model 变量时,它也修改了 originalModel 变量,因为它是静态的,这不是我的意图。我想保持 originalModel 变量静态,但只是将其内容复制到 model 变量

class Helper{
  static var originalModel: [MyModel]? =  nil 

  static func modifyDataSourceBigView () -> [MyModel]? {
    if let model = originalModel {
      //model.removeAtIndexPath
      // Some other staff to adapt the model
      return model
    }
  }

  static func modifyDataSourceSmallView () -> [MyModel]? {
    if let model = originalModel {
      //model.removeAtIndexPath
      // Some other staff to adapt the model
      return model
    }
  }
}

【问题讨论】:

    标签: ios swift static uicollectionview


    【解决方案1】:

    出现问题是因为数组 [MyModel] 包含对 MyModel 对象的引用。您的函数返回originalModel副本,其中包含对原始 MyModel 对象的引用。您有两种方法可以解决您的问题:

    1. MyModel 声明为struct,而不是class,它的实例将按值传递,而不是按引用传递;
    2. 执行复制对象方法,例如使MyModel符合NSCopying并实现copyWithZone()方法。

    【讨论】:

      【解决方案2】:

      您可以复制您的静态数组,如下所示。但它不会是深拷贝,如果你想深拷贝你的对象数组,请参考link

      class Helper {
      
          static var originalModel: [MyModel]? =  nil
      
          static func modifyDataSourceBigView () -> [MyModel]? {
              if var model = originalModel{
                  model.remove(at: 0)
                  // Some other staff to adapt the model
                  return model                
              }
      
              return nil
          }
      
          static func modifyDataSourceSmallView () -> [MyModel]? {
              if var model = originalModel {
                  model.remove(at: 0)
                  // Some other staff to adapt the model
                  return model
              }
      
              return nil
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2015-01-04
        • 2012-05-10
        • 2016-03-05
        • 1970-01-01
        • 2014-07-24
        • 2012-09-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多