Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 282
fillky Avatar asked Jun 19 '14 13:06

fillky


2 Answers

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

like image 75
Duncan C Avatar answered Nov 15 '22 08:11

Duncan C


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

like image 31
Jeffery Thomas Avatar answered Nov 15 '22 08:11

Jeffery Thomas