Questions about a readonly @property in ARC

前端 未结 3 492
死守一世寂寞
死守一世寂寞 2020-12-20 21:10

In my interface (.h) file, I have

@property(readonly) NSString *foo;

and in my implementation (.m) file, I have

@synthesize         


        
相关标签:
3条回答
  • 2020-12-20 21:19

    It is here as a declaration to the rest of your code.
    When you a access the property of this class from an other part of your code, you need to know if the object you get is strong or weak.

    It used to be more obvious when ARC didn't exists, because the programmer needed this information. Now, ARC makes a lot of things transparent, so it is true, you might wonder why it is still here.


    Why can’t the compiler intelligently deduce a default setting for a read-only property?

    I assume it would be pretty easy to set the convention that no keyword means strong or means weak. If it hasn't been done, they surely had a reason.

    0 讨论(0)
  • 2020-12-20 21:28

    With the latest version of Xcode and recent clang compilers, this error no longer occurs. You can specify a property as @property(nonatomic, readonly) NSObject *myProperty; in the interface, synthesize it in the implementation, and the resulting ivar is assumed to be strong. If you want to be explicit or choose weak, you can do so in the original property, like @property(nonatomic, readonly, retain). Objective-C is incrementally becoming less redundant.

    0 讨论(0)
  • 2020-12-20 21:36

    You've declared a @property that doesn't have a backing ivar. Thus, when the compiler sees @synthesize, it tries to synthesize a backing ivar for you. But you haven't specified what kind of ivar you want. Should it be __strong? __weak? __unsafe_unretained? Originally, the default storage attribute for properties was assign, which is the same as __unsafe_unretained. Under ARC, though, that's almost always the wrong choice. So rather than synthesizing an unsafe ivar, they require you to specify what kind of ivar you want.

    0 讨论(0)
提交回复
热议问题