Best way to set a retained property to a newly created object

前端 未结 4 1860
南笙
南笙 2021-01-05 22:21

Which is the best way to handle creating an object to live in a retained property? I\'ve included several examples.

Assume the property is:

@property         


        
4条回答
  •  情歌与酒
    2021-01-05 22:29

    If in initialization of the object which holds the variable:

    1) no. it's bad form to call through accessors in partially constructed states (e.g. init, dealloc)

    2) no. it's bad form to call through accessors in partially constructed states (e.g. init, dealloc)

    3) correct.

    Exception: If your ivars are not private and you are in the implementation of a subclass of the type which declared the property, then you must also check to see if the parent class initialized the property. it's best to make the properties private or otherwise not directly accessible to subclasses.

    4) no. it's bad form to call through accessors in partially constructed states (e.g. init, dealloc)

    When you're working with a fully constructed instance:

    1) this is fine when readbaility is more important than keeping your heap sizes low.

    2) bad. the object returned from the getter is not necessarily the object you assigned.

    3) bad. may introduce a leak if _myProperty is not nil.

    4) best

提交回复
热议问题