Property name starting with 'new' prefix l

2020-06-22 02:17发布

问题:

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)).