What is self in ObjC? When should i use it?

前端 未结 6 2233
無奈伤痛
無奈伤痛 2020-11-28 14:36

What does self mean in Objective-C? When and where should I use it? Is it similar to this in Java?

6条回答
  •  臣服心动
    2020-11-28 15:20

    Two important notes:

    1. The class itself, e.g. UIView (I'm NOT talking about a UIView object) is itself an object, and there is a self associated with it. So for example, you can reference self in a class method like this:

      // This works
      +(void) showYourself { [self performSelector: @selector(makeTheMostOfYourself)]; }
      
      // Class method!
      +(void) makeTheMostOfYourself { }
      
    2. Note that the compiler does NOT raise any warnings or errors, even if the self you mean to reference is an object and not a class. It is VERY easy to cause crashes this way, for example:

      // This will crash!
      +(void) showYourself { [self performSelector: @selector(makeTheMostOfYourself)]; }
      
      // Object method!
      -(void) makeTheMostOfYourself { }
      
      
      
      // This will crash too!
      -(void) showYourself2 { [self performSelector: @selector(makeTheMostOfYourself2)]; }
      
      // Class method!
      +(void) makeTheMostOfYourself2 { }
      

      Sadly, this makes class methods a bit harder to use, which is unfortunate because they are a valuable tool for encapsulation through information hiding. Just be careful.

提交回复
热议问题