aaronium112
aaronium112

Reputation: 3088

How do Class Methods work in iOS?

I've used class methods and even written them following along with books. I've heard of them described as factory methods. I understand that they operate on a class itself, rather than an instance of a class. I've also read up on them but I still don't feel like I really understand them.

Can you offer any good metaphors or key distinctions that would help myself and others understand class methods?

Part of my problem seems to be the dynamic between when you are operating on a class vs an instance of a class. That remains a slippery issue as well which seems very relevant in this discussion.

Could someone try and relate class methods to a real world metaphor?

I've explained resistance to my friends with no science background like this. It's not perfect but it helps a lot.

Imagine water flowing through a pipe unimpeded. Now imagine we have a butterfly valve (just like the image attached). Let's close the valve 80% of the way so much less water can flow through. The valve is "like" a resistor in a electric circuit and the water is "like" the electricity and the pipe is the wire. To increase the resistance of the resistor is "like" progressively closing the valve in the pipe of flowing water.

Is there a way to draw a metaphor between a car factory, a peanut butter sandwich or something similarly tangible?

Thanks for the help.

-A

alt text

Upvotes: 3

Views: 1578

Answers (1)

Chuck
Chuck

Reputation: 237110

Think of a class as a soda machine. The cans (instances) are generally the more useful item, but the machine itself is a thing that you interact with as well. When you push certain buttons (class methods) on the machine, it will give you cans. There may also be buttons that tell you the price of soda, or return your coin, or anything else the machine's creator (you) thought to give the machine buttons for. The machine is definitely distinct from the cans — it just defines what kind of soda you can get.

(For clarity: This isn't actually a class-instance relationship in the example. Sodas are not instances of a soda machine, just like water is not actually electricity. But it is a good mirror of how you relate to and interact with classes and instances in a language like Objective-C.)

Upvotes: 5

Related Questions