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?
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.
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."
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.
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;
If something's declared in your category's interface, its definition belongs in your category's implementation.
I wrote two articles on this, though the concept is slightly different from the question you're asking.
This is a LOT better than method swizzling, at least: way safer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With