As the title says, I share the same logic between an UIViewController and an UITableViewCell, which send some info to a server and do some calculus.
I’m having the problem that the replicated code is bigger as time passes but I don’t know how to factorize this because the clases are different objects and each function call instance variables.
Which is a good way to re-factorize the code so I don’t have to change the same code twice everytime?
The simplest way of refactoring a duplicated code is to make a method out of the common part. An important question is where to put it. When the objects are related, you can put the common code in their common ancestor; when they are not related, you might consider creating a helper class with only class methods, or defining a C-style freestanding function with the body of your method.
In case the objects are unrelated and you need to use their instance variables, there may be an opportunity to extract a common object. Move all common instance variables needed for the duplicated code into the new common object, along with the code that uses these variables. If the variables are also needed in the original classes from which you have extracted the common part, add getters and setters as needed. Create an ivar for the extracted class, and use its properties in place of the instance variables.