[Objective-C]为现有对象增加额外的实例变量/数据

想到要如何为所有的对象增加实例变量吗? 使用Category可以很方便地为现有的类增加方法,但却无法直接增加实例变量(有为此使用查表法的,也算曲线救国吧)。不过从Mac OS X v10.6开始,系统提供了Associative References,这个问题就很容易解决了。


我根据Objective-C Reference中的示例修改了一下,直接上代码了。重点是其中objc_setAssociatedObject的使用, 并且其中Key是一个地址,而不是字串。

#import <Foundation/Foundation.h>
#import <objc/runtime.h>
 
int main (int argc, const char * argv[]) {
 
    @autoreleasepool {
	/*Seciton 0. 关联数据的Key和Value*/
    static char overviewKey;
	static const char *myOwnKey = "VideoProperty\0";
	static const char intValueKey = 'i';
 
    NSArray *array = [[NSArray alloc]
            initWithObjects:@ "One", @"Two", @"Three", nil];

    // For the purposes of illustration, use initWithFormat: to ensure
    // we get a deallocatable string
    NSString *overview = [[NSString alloc]
            initWithFormat:@"%@", @"First three numbers"];
	NSString *videoKeyValue = @"This is a video";
	NSNumber *intValue = [[NSNumber alloc]initWithInt:5];

	/*Section 1. 关联数据设置部分*/
    objc_setAssociatedObject (
            array,
            &overviewKey,
            overview,
            OBJC_ASSOCIATION_RETAIN
        );
        [overview release];

	objc_setAssociatedObject (
	    array,
	    myOwnKey,
	    videoKeyValue,
	    OBJC_ASSOCIATION_RETAIN
	);

	objc_setAssociatedObject (
	    array,
	    &intValueKey,
	    intValue,
	    OBJC_ASSOCIATION_RETAIN
	);
 
    /*Section 3. 关联数据查询部分*/
    NSString *associatedObject =  (NSString *) objc_getAssociatedObject (array, &overviewKey);
    NSLog(@"associatedObject: %@", associatedObject);
	NSString *associatedObject2 = (NSString *) objc_getAssociatedObject(array, myOwnKey);
	NSLog(@"Video Key value is %@", associatedObject2);
	NSString *assObject3 = (NSString *) objc_getAssociatedObject(array, &myOwnKey);
	if( assObject3 )
	{
		NSLog(@"不会进入这里! assObject3 应当为nil!");
	}
	else
	{
		NSLog(@"OK. 通过myOwnKey的地址是得不到数据的!");
	}
    NSNumber *assKeyValue = (NSNumber *) objc_getAssociatedObject(array, &intValueKey); 
	NSLog(@"Int value is %d",[assKeyValue intValue]);
	
	/*Section 3. 关联数据清理部分*/
    objc_setAssociatedObject (
            array,
            &overviewKey,
            nil,
            OBJC_ASSOCIATION_ASSIGN
        );

	objc_setAssociatedObject (
	    array,
	    myOwnKey,
	    nil,
	    OBJC_ASSOCIATION_ASSIGN
	);
	
	objc_setAssociatedObject (
	    array,
	    &intValueKey,
	    nil,
	    OBJC_ASSOCIATION_ASSIGN
	);
        [array release];
 
    }
    return 0;
}

*可以使用如下指令在命令行下编译:

  clang -o associates -g -x objective-c++ -Wall associates.mm -framework Foundation -lobjc



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值