Reseting Class Instances

I have an app that I’m working on and it has one class, with instance variables and functions, that I developed. My class instance variables are arrays and are initialized with literal values.

I want to be able to “reset” all my instances and or class instance without having to end the app and restart it. What’s the best practice to do this?

The only thing that I’ve come up with so far is setting up an instance of
my class as an optional. I’m not sure if that’s good practice and I’m also
not sure if I’ve coded everything correctly.

Here’s an example(this is not my actual code!): myApp
//class file
Class myNewClass {
var aString = [“A”,“B”,C"]
var aDigit = [1,2,3]
}

//viewcontroller code

var myClassInstance: myNewClass? = myNewClass

//UIButton that resets my class instance
@IBAction func resetClass(_ sender: UIButton)
{
myClassInstance = nil
var myClassInstance: myNewClass? = myNewClass
}

So, will this code work and or should I even try to make a class instance
into an optional?

If this code won’t work then what is a better way to “reset” my class and or it’s instance variables without ending the app?

Thanks for any and all help!

Gary

Hi Elearner,

Setting the variable myClassInstance as optional, is depend with the use you use the optional in your code.
To make it sort if the only reason you used it for the reset function, I will do it in a different approach:

  • remove the optional from the class definition
  • replace the code in resetClass action to: myClassInstance = myNewClass()
    If you need to use the optional in your code, you can keep it and just replace the code in reset function.

I think it the simple solution to your problem by the code. But if you interesting we can start discussion on other approaches.

Hi ofiron,

Thanks for your quick response.
I’ll give your suggestion a try.

Thanks,
Gary

@ofiron suggestion should be followed if you don’t want to handle the unwrapping of your variable each time you need it, especially if it never needs to be nil.
Also, do you want to reset a single instance or a variable number of instance of this object ?

The technique is good, but if you can use ‘struct’ instead of ‘class’ then you can safely put the reset function into the struct itself.

struct MyNewThing {
    var aString = ["A","B",C"]
    var aDigit = [1,2,3] 
    func reset() {
        self = MyNewThing()
    }
}

It’s not safe to do that inside a class.


C. Keith Ray
Senior Software Engineer / Trainer / Agile Coach

Thanks for the suggestion, Keith!
I’m beginning to believe, that in most cases, it’s better to start with
a struct vs a class.

Gary