Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
754 views
in Technique[技术] by (71.8m points)

xcode - Why is self allowed in static context in objective c

Why is using self allowed in static context in Objective-C?

I thought it was allowed and then I encountered memory errors that took me a week to find out that self is not an alias for calling other static methods from the class instead of typing the class name.

Xcode and its compiler seems very smart at finding common pitfalls, why isn't it even generating a warning about something like that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  1. There is no such thing as a "static context" in Objective-C. What we have instead are "class methods". They definitely are not "static" methods.
  2. Class methods (ones prefixed with a +) are really just instance methods on a particular Class object. (did your mind just explode?) And since you have a self variable accessible in an instance method, you naturally have a self variable accessible in the class method as well.
  3. In a class method, self points to the class itself.
  4. Just as you can do [self performAction] inside an instance method to invoke methods on this particular instance, you can do [self performClassAction] inside a class method to invoke methods on this particular class.
  5. All Class objects are subclasses of NSObject. So you can use any NSObject instance method on any Class object. (did your mind just explode again?)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...