开发者

What is the difference between an instance variable/method and a class variable/method in Objective-C?

I've seen many other questions on this same topic but they're not very clear to me, someone new to Objective-C.

I need a plain english explanation. 'Coder speak' i开发者_JAVA百科s much too difficult for me to understand at this point in my learning.


An instance method or variable applies to that instance. A class method (classes in Objective-C don't have variables, though they can be simulated in various ways) applies to the whole class.

Consider the quintessential Dog class, which derives from the Mammal class (and so on up the tree of life.) A particular dog has a name and a collar and an owner--those are its properties. A particular dog may -bark or -chaseBall or -buryBoneInBackyard--those are its methods.

The Dog class, on the other hand, has different methods. The Dog class has a +globalPopulation and may instantiate itself with a +dogWithDNA: factory method. The Dog class will have an +isExtinct method indicating whether the species as a whole is extinct (it's not, of course.)

In short: class methods affect the entire class, while instance methods affect a particular instance of a class.


First, Objective-C does not have class variables. There are things that act sorts like class variables modally, but they aren't true class variables (see "static variables").

In Objective-C, every class is effectively an instance of a class. Thus, a class method is simply a method that applies to the class. They can be inherited and overridden.


Instance variables (ivars) and instance methods exist on each instance. There is one ivar per instance. Instance methods can not be called on classes.

Class variables^ and class methods do not not exist on instances, they exist on the class. That means that there will only ever be one class variable in the entire application regardless of how many instances are created. Class methods can be called without an instance*, so they kind of act like normal C functions. Because class methods are not attached to an instance, class methods can not access ivars.

^ Objective-C doesn't have class variables per se. "Class variables" are effectively static global variables in C.

* technically, a class is an instance, so class methods are actually instance methods in a sense.


A class is like a mold for something, that you can fill with plaster.

So a class level method is something that you can see and reach and use, without ever having to make a single object.

An instance is like pouring plaster into the mold and getting something out. You stamp out as many as you need; an instance variable then is a place on that object to hold something, and an instance method is something you can do with only that single object, not all of them.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜