Property name starting with 'new' prefix leads to BAD_ACCESS error in iOS

孤街醉人 提交于 2020-01-13 01:34:41

问题


My property was declared in my NSManagedObject class with name "newPrice", which leads to "zombie object". After some hours of debugging I figured out that there is problem with method which is releasing this object but not retaining it. After renaming this property to "priceNew" everything goes well. I don't understand why this is causing problem.

Declaration of property:

@property (nonatomic, retain) NSNumber * newPrice;

This call causing problem:

[self setPieceStateWithPrice:self.action.newPrice];

After passing renamed argument like self.action.priceNew everything goes well...


回答1:


Don't do that.

In Objective-C naming conventions, methods whose names begin with new are expected to return a retained object. With ARC, that naming convention becomes a requirement. That means that a normal, ARC-compiled method should never start with the name new because the compiler will assume that it already has a retain count of 1.

To quote the docs:

You own any object you create

You create an object using a method whose name begins with “alloc”, “new”, “copy”, or “mutableCopy” (for example, alloc, newObject, or mutableCopy).




回答2:


Properties have methods automatically synthesized for them. So, having a property implies have a method with the same name.

Methods which begin with alloc, copy, init, mutableCopy, and new have special assumptions about how they handle memory. Unless you have a very good reason, you should avoid these prefixes.

From Clang 3.5 documentation | Objective-C Automatic Reference Counting | Retained return values

A function or method which returns a retainable object pointer type may be marked as returning a retained value, signifying that the caller expects to take ownership of a +1 retain count.

Methods in the alloc, copy, init, mutableCopy, and new families are implicitly marked attribute((ns_returns_retained)). This may be suppressed by explicitly marking the method attribute((ns_returns_not_retained)).



来源:https://stackoverflow.com/questions/24308162/property-name-starting-with-new-prefix-leads-to-bad-access-error-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!