search

Home  >  Q&A  >  body text

objective-c - ios开发中self和下划线的区分

今天碰到一个问题,就是用到懒加载的时候,我用了self,结果报错直接蹦了,

我们老师说这是self递归引用了,可我还是不明白它们之间的区别

黄舟黄舟2829 days ago893

reply all(3)I'll reply

  • PHP中文网

    PHP中文网2017-04-27 09:04:53

    Self. _x is the automatically created instance variable.
    For example, you define the following attribute:

    @property(nonation, strong) NSString *x;

    There is a bunch of hidden (simplified) code as follows:

    NSString *_x;
    
    -(NSString *)x {
        return _x;
    }
    
    -(void)setX:(NSString *)x {
        _x = x;
    }

    I guess your lazy loading code overloads the get method of the attribute. Self.x actually calls the [self x] method. If you use self.x in the get method, then self.x calls it again. , [self x] method, this is infinite recursion.

    reply
    0
  • 黄舟

    黄舟2017-04-27 09:04:53

    If it is referenced, there will be no difference. It is the same pointer. If it is assigned, there is a difference. self.xx=oo First, xxretaincount -1 and then retain oo _XX is copied to point directly to oo. There is no retain step. Nor

    reply
    0
  • 曾经蜡笔没有小新

    曾经蜡笔没有小新2017-04-27 09:04:53

    I just guessed that you might be:

    self.some = [self some];
    -(type)some{
        self.some = [...];
    }
    

    Then when you call self.some, it is equivalent to using [self some], and self.some in some calls [self some] again. . . A loop is formed. . .

    Underscore means direct access, bypassing set and get. .

    reply
    0
  • Cancelreply