iosarraysswiftindexpathuinib

persist array of UINib


I have an issue and I can't find any information out there... The thing is I have an Array of custom UINibs which each have their standard Class after I created them as a CustomTableViewCell.

import UIKit

class TestCell1: UITableViewCell {

override func awakeFromNib() {
    super.awakeFromNib()
    // Initialization code
}
}

In this array I store 3 UINibs which are TableViewCells and I want to persist their reorder after I drag and dropped them.

I have for now created an global Array which is accessible for all my ViewControllers.

class Test {
static var globalArray: [UINib] = [UINib(nibName: "ToDoCell", bundle: nil)]}

under viewDidLoad I have tried something like this:

    Test.globalArray.append(test1Nib)
    Test.globalArray.append(test2Nib)
    Test.globalArray.append(test3Nib)
    Test.globalArray.append(test4Nib)

I now struggle with persist their order in the array. I have tried Realm, Core Data and UserDefaults but I can't find any solution. But I Guess the issue is that they are not happy with UINibs

These Nibs each represent a Cell in a UITableView and after the user was able to move the Cells as he like the order should of course persist after reopen the App. So if I get it right I only need to persist the IndexPath but I can't find any useful information about that...

I hope I can find help in here - please not that I just started Swift and iOS Development and maybe what I try is not possible at all - maybe you have a quick hint, some tutorials, snippets, books or some thoughts or something in any direction. I'm willing to learn and maybe I just interpret something wrong would be great! thanks a lot!


Solution

  • You already discovered that storing an array of UINib instances is not possible. This is because it wouldn’t make sense to do so. The nibs are an implementation detail of your view layer. Things you save belong to the model layer which should be independent of the view layer. You should be able to take the code of your model layer and put it without changes into a desktop app, a web app or even an Android app. This of course won’t be possible if it references any iOS-Specific view classes such as UINib.

    The simplest possible thing you could do is to make your model an array of strings. Those strings could be your nib names. This would be easy to serialize and as easy to use when instantiating your table view cells.