Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C categories: Can I add a property for a method not in my category?

I want to use a category to make a method on the original class available as a property as well.

Class A:

@interface ClassA
- (NSString*)foo;
@end

Class A category

@interface ClassA (Properties)
- (void)someCategoryMethod;
@property (nonatomic, readonly) NSString *foo;
@end

Now when I do this, it seems to work (EDIT: Maybe it doesn't work, it doesn't complain but I am seeing strangeness), but it gives me warnings because I am not synthesizing the property in my category implementation. How do I tell the compiler everything is actually just fine since the original class synthesizes the property for me?

like image 382
Alex Wayne Avatar asked Mar 26 '10 02:03

Alex Wayne


People also ask

What is a category in Objective-C and when is it used?

Categories provide the ability to add functionality to an object without subclassing or changing the actual object. A handy tool, they are often used to add methods to existing classes, such as NSString or your own custom objects.

How do you declare a category in Objective-C?

Let's create a category that add functionality to UIFont class. Open your XCode project, click on File -> New -> File and choose Objective-C file , click Next enter your category name say "CustomFont" choose file type as Category and Class as UIFont then Click "Next" followed by "Create."

What is property in Objective-C?

Objective-C properties offer a way to define the information that a class is intended to encapsulate. As you saw in Properties Control Access to an Object's Values, property declarations are included in the interface for a class, like this: @interface XYZPerson : NSObject.


3 Answers

Here's the warning you're getting:

warning: property ‘foo’ requires method '-foo' to be defined - use @synthesize, @dynamic or provide a method implementation

To suppress this warning, have this in your implementation:

@dynamic foo;

like image 62
codewarrior Avatar answered Sep 20 '22 05:09

codewarrior


If something's declared in your category's interface, its definition belongs in your category's implementation.

like image 40
Josh Freeman Avatar answered Sep 22 '22 05:09

Josh Freeman


I wrote two articles on this, though the concept is slightly different from the question you're asking.

  1. Add properties to categories without touching the base class: http://compileyouidontevenknowyou.blogspot.com/2012/06/adding-properties-to-class-you-dont.html
  2. Access iVars from categories: http://compileyouidontevenknowyou.blogspot.com/2012/06/if-you-want-to-keep-everything-in-your.html

This is a LOT better than method swizzling, at least: way safer.

like image 38
Dan Rosenstark Avatar answered Sep 21 '22 05:09

Dan Rosenstark