search

Home  >  Q&A  >  body text

Objective-c - Regarding the problem of using self in the getter method to cause an infinite loop?

  1. Attributes:
    @property (strong, nonatomic) NSArray *dataArr;

  2. Rewrite the getter method (the code is about lazy loading, but this is not the point)

 - (NSArray *)dataArr{
    //1. 判断是否为空
    if(_dataArr == nil){ //不能写self.dataArr
        self.dataArr = @[ //可以写self.dataArr
                         
                         .........
                         
                        ];
    }
    return _dataArr;
    
}

What I know now is that using self.dataArr will call the attribute's getter方法 and setter方法

So I think if in parentheses cannot be used self.dataArr otherwise it will be an infinite loop

But I don’t know why you can use self.dataArr in if braces?

Is it because the curly brackets are assignments, so only setter方法 will be called?

Can I write self.dataArr after return?

It’s a bit confusing, please give me some answers...

仅有的幸福仅有的幸福2857 days ago698

reply all(1)I'll reply

  • 高洛峰

    高洛峰2017-05-02 09:31:01

    . . .
    Inside the bracesself.dataArr = @[] will only adjust the setter, so there is no problem, but return self.dataArr; will call the getter, causing an infinite loop
    You can log it yourself or track the breakpoints to find out.
    Suitable tutorial

    reply
    0
  • Cancelreply