Objective-c - Regarding the problem of using self in the getter method to cause an infinite loop?
仅有的幸福
仅有的幸福 2017-05-02 09:29:01
0
1
674
  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...

仅有的幸福
仅有的幸福

reply all(1)
小葫芦

. . .
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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template