0

I use this code to adapt the model of a collection view. The problem is that when I modify the model variable, it also modify the originalModel variable because it's static which is not my intention. I want to keep the originalModel variable static but just copy it's content in the model variable

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
    }
  }
}
mixel
  • 25,177
  • 13
  • 126
  • 165
User1238
  • 87
  • 8

2 Answers2

1

The problem occur because array [MyModel] contains references to MyModel objects. Your functions return you copies of originalModel, that contains references to original MyModel objects. You have two ways to fix your issue:

  1. Declare MyModel as struct, not class, and it instances will be passed by value, not by reference;
  2. Perform copy object methods, for example make MyModel conform to NSCopying and implement copyWithZone() method.
Yury
  • 6,044
  • 3
  • 19
  • 41
0

You can copy your static array like below. But it won't be deep copy, if you would like to deep copy your array of objects just refer this 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
    }
}
Community
  • 1
  • 1
Natarajan
  • 3,241
  • 3
  • 17
  • 34