Adding properties to an objective-C category

Source: Internet
Author: User

Http://www.davidhamrick.com/2012/02/12/Adding-Properties-to-an-Objective-C-Category.html

Let's say you have a category that needs to store some information. Unfortunately you can't add an instance variable, but you can add something called an associated reference. From the documentation:

Associative references, available starting in Mac OS X v10.6, simulate the addition of object instance variables to an existing class

To create an association you useobjc_setAssociatedObjectFunction
And to retrieve an association useobjc_getAssociatedObjectMethod.

Using an associated reference as storage for a property

We can use this technique to make a built in class have a property that we want. In this example, I am storing the name of a style that I want to assign to a uiview.

@interface UIView (DHStyleManager)@property (nonatomic, copy) NSString* styleName;@end
#import "UIViewDHStyleManager.h"NSString * const kDHStyleKey = @"kDHStyleKey";@implementation UIView (DHStyleManager)- (void)setStyleName:(NSString *)styleName{objc_setAssociatedObject(self, kDHStyleKey, styleName, OBJC_ASSOCIATION_COPY);}- (NSString*)styleName{return objc_getAssociatedObject(self, kDHStyleKey);}@end

When instances of uiview are released they will also release their associated references.

This technique let's use set this custom property on plain old uiviews. If you only need to do something simple like add a property, this provides a nice alternative to subclassing.

#import UIViewDHStyleManager.h"UIView* v = [[[UIView alloc] init] autorelease];v.styleName = @"someStyleName";NSLog(@"v = %@",v.styleName); //Logs 'someStyleName'

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.