Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will the compiler auto-synthesize an ivar for a property declared in a category?

Before so-called "Modern Objective-C", when creating a new property in category, we needed to implement setter and getter methods. Now, we don't have to do @synthesize; the compiler will automatically create the methods and an instance variable.

But normally, we cannot add instance variables to a category, so what happens if we add a new property in a category with modern Objective-C? Does the compiler create an ivar for us?

like image 756
IPaPa Avatar asked Feb 19 '23 20:02

IPaPa


2 Answers

You can declare a property in a category, which is equivalent to declaring the getter and (if readwrite) setter selectors.

The compiler will not automatically synthesize the getter and setter methods in your category implementation. If you don't explicitly define them in the category implementation, the compiler will issue a warning. You can use @dynamic in the category implementation to suppress the warning. You cannot use @synthesize in the category implementation; the compiler will issue an error if you try.

The compiler will not add an instance variable for a property declared in a category. You cannot explicitly add instance variables in a category, and you can't trick the compiler into doing it using a property.

I tested my claims using Xcode 4.5.1 targetting iOS 6.0.

like image 154
rob mayoff Avatar answered Mar 08 '23 23:03

rob mayoff


Actually I don't know when we were able to add property in categories.

From Apple Docs:

A category allows you to add methods to an existing class—even to one for which you do not have the source.

and

Class extensions are like anonymous categories, except that the methods they declare must be implemented in the main @implementation block for the corresponding class. Using the Clang/LLVM 2.0 compiler, you can also declare properties and instance variables in a class extension.

and this method is used to add storage to an object without modifying the class declaration (in case you couldn't modify or don't have access to source codes of class)

Associative references, available starting in OS X v10.6, simulate the addition of object instance variables to an existing class. Using associative references, you can add storage to an object without modifying the class declaration. This may be useful if you do not have access to the source code for the class, or if for binary-compatibility reasons you cannot alter the layout of the object.

So your question for me seems to be incorrect.

Source: Apple Docs - The Objective-C Programming Language

like image 29
Nekto Avatar answered Mar 09 '23 00:03

Nekto