Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
747 views
in Technique[技术] by (71.8m points)

objective c - Is self.iVar necessary for strong properties with ARC?

  1. If I declare a property strong, like so:

    @property (strong, nonatomic) UIView *iVar;
    

    When I'm setting it, does it matter if I do iVar = ... or self.iVar = ...? It seems that with ARC, they do the same thing.

  2. If I only declare the instance variable (not the @property), e.g., BOOL selected, does that mean it's inferred to be __unsafe_unretained (since there's no property specifying it to be strong), or must I explicitly specify that?

It seems like I may have answered my own questions above in answering ARC: How to release static variable?, but I'm still slightly confused on the above questions.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From a memory management perspective, using ivar = ... or self.property = ... (note: there's no such thing as self.ivar) are the same. However, using ivar = ... doesn't invoke the setter while self.property = ... does. This has 3 important ramifications, in no particular order:

  1. If the property is not marked nonatomic, then access to the underlying ivar will not take the lock and you will be breaking the atomicity implications.
  2. If the property is overridden, either by you or by a subclass, the overridden setter will not be invoked.
  3. KVO notifications will not be sent.

As for only declaring the ivar, it has the same memory management semantics as declaring a local variable. This is documented in section 4.4 of the Objective-C Automatic Reference Counting document, but basically, if it's an object, it will be inferred to be __strong.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...