Objective C - Memory management question?

后端 未结 4 1230
-上瘾入骨i
-上瘾入骨i 2021-01-28 21:35

I know that when i have a property for an object which is set to retain or copy i must do the following.

Object *o = [[Object alloc] init];
self.myObject = o;
[o         


        
4条回答
  •  -上瘾入骨i
    2021-01-28 21:59

    You don't need to have any properties. Obj-C didn't even have them at all until a couple of years ago with Obj-C 2. Properties are a convenience - they give you some memory management without you writing boilerplate code (the access methods are synthesized for you), and you can use dot notation, which some people are more familiar with than the usual Obj-C syntax.

    Having said that properties take care of memory management for you, that's only partially true. You still need to set all properties to nil in your dealloc method. So that really doesn't buy you much, since without properties you'd still need to release each object in dealloc.

    The big benefit is that properties handle reference counting for you when assigning objects from one place to another. You don't have to write the getters and setters manually. For this reason, I like properties. Plus, clang is gaining the ability to have properties where you only need the @property line, no need for a backing variable, and no need for an @synthesize line. One-line properties are a win in my book. (OK, two lines, you need to add a line to dealloc too :)

提交回复
热议问题