0
\$\begingroup\$

I'm trying to use inheritance in UIViewController where base class has XIB in storyboard. I'm troubling with initiating different children classes with that XIB.
I cannot use XIB file separately instead of storyboard because it has static UITableViewCells.

So here is how I'm managing it currently using object_setClass method in SWIFT:
Parent Class:

class MeetingViewController: UITableViewController {

    private(set) var project: CDProject?
    private(set) var meeting: CDMeeting?

    static func initWith(project: CDProject?, meeting: CDMeeting?) -> MeetingViewController {
        let storyboard = UIStoryboard(name: "Meeting", bundle: nil)
        let meetingVC = storyboard.instantiateViewController(withIdentifier: "MeetingVCId") as! MeetingViewController
        meetingVC.project = project
        meetingVC.meeting = meeting
        return meetingVC
    }
}

Child Class-1:

class MeetingInfoViewController: MeetingViewController {

    static func initWith(meeting: CDMeeting) -> MeetingInfoViewController {
        let meetingVC = MeetingViewController.initWith(project: nil, meeting: meeting)
        object_setClass(meetingVC, MeetingInfoViewController.self)
        return meetingVC as! MeetingInfoViewController
    }
}

Child Class-2:

class MeetingCreateViewController: MeetingViewController {

    static func initWith(project: CDProject) -> MeetingCreateViewController {
        let meetingVC = MeetingViewController.initWith(project: project, meeting: nil)
        object_setClass(meetingVC, MeetingCreateViewController.self)
        return meetingVC as! MeetingCreateViewController
    }
}

This is working very fine, not any issue; but I'm just curious if:
1 there's any other way to handle this scenario?
2 this approach has any side-effects?
3 this can be improved somehow?

Also feel free to point out other things than initialisation!

\$\endgroup\$
  • \$\begingroup\$ I'm surprised this works. What happens when you try to set a property that only the child class has? \$\endgroup\$ – trapper Dec 21 '18 at 3:32
1
\$\begingroup\$
  1. There isn't another way to handle this scenario. Storyboard VC's can't be subclassed without replicating the UI also.

  2. I'm surprised this works at all. object_setClass just changes the isa pointer, so the memory is still set up for the parent class, not the child. It will probably crash if you try to set an instance variable that doesn't exist in the parent.

  3. Refactor the two VC's into one (since the UI is the same after all), and use composition for the differences instead.

\$\endgroup\$
  • \$\begingroup\$ I'm not considering to have any public/private instant vars for any of children.... \$\endgroup\$ – D4ttatraya Dec 21 '18 at 5:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.