开发者

Objective-C member initializiation of autoreleased objects

开发者 https://www.devze.com 2022-12-11 06:02 出处:网络
Hey so if I have some property like @interface MyClass { NSArray* myArray; } @end @property (retain, nonatomic) NSArray* myArray;

Hey so if I have some property like

@interface MyClass {
   NSArray* myArray;
}
@end

@property (retain, nonatomic) NSArray* myArray;

In my init method should I do something like

myArray = [[NSArray array] retain];

Or

self.myArray = [NSArray array];

I would think the former would be preferred as it is more clear what is going on? I guess another way to phrase it should be, should you interact with a member's properties inside the implementation or strictly use the members t开发者_运维问答hemselves?


The first is preferred because if you go through the accessor it can trigger KVO notifications which can cause weird issues if your subclass the object.


Aside from maintaining OOP paradigms, a big point of the setter is to properly release previously retained values. Since you're in init, it's generally safe to assume there is no existing value, so you don't really gain anything out of using the setter.

0

精彩评论

暂无评论...
验证码 换一张
取 消