zoukankan      html  css  js  c++  java
  • objc_getAssociatedObject objc_setAssociatedObject关联

    关联是指把两个对象相互关联起来,使得其中的一个对象作为另外一个对象的一部分。

    创建关联要使用到Objective-C的运行时函数:objc_setAssociatedObject来把一个对象与另外一个对象进行关联。该函数需要四个参数:源对象,关键字,关联的对象和一个关联策略。

    用法:

    NSObject *object=[[NSObject alloc] init];
    static char associatekey;
    objc_setAssociatedObject(object, &associatekey, @"object value", OBJC_ASSOCIATION_ASSIGN);

    获得关联对象
    NSString * associatedObject = (NSString *)objc_getAssociatedObject(object, &associatekey);

    断开关联
    objc_setAssociatedObject(object, &associatekey, nil, OBJC_ASSOCIATION_ASSIGN);

    需要导入#import <objc/runtime.h>

    下面是完整的例子

    #import <Foundation/Foundation.h>
    @class Address;
    @interface Student : NSObject

    @property (nonatomic,copy) NSString *stuName;
    @property (nonatomic,assign) NSInteger age;
    @property (nonatomic,weak) Address *address;

    @end

    #import "Student.h"

    @implementation Student

    @end

    #import "Student.h"

    @interface Student (StudentCategory)

    @property (nonatomic,copy) NSString *nickName;

    @end


    #import "Student+StudentCategory.h"

    //objc_getAssociatedObject 是在runtime下的,所以必须导入runtime库。
    #import <objc/runtime.h>

    @implementation Student (StudentCategory)

    // objc_setAssociatedObject 用在category里面的property, category里面的property必须要手动实现getter和setter方法。
    -(NSString*)nickName
    {
    /*
    NSObject *object=[[NSObject alloc] init];
    static char associatekey;
    objc_setAssociatedObject(object, &associatekey, @"object value", OBJC_ASSOCIATION_ASSIGN);

    NSString * associatedObject = (NSString *)objc_getAssociatedObject(object, &associatekey);

    objc_setAssociatedObject(object, &associatekey, nil, OBJC_ASSOCIATION_ASSIGN);
    */



    //category不会自动合成实例变量_nickName,所以不能直接return _nickName;
    return objc_getAssociatedObject(self,@selector(nickName));
    }

    -(void)setNickName:(NSString *)value
    {
    //category不会自动合成实例变量_nickName,所以不能直接_nickName=value;
    objc_setAssociatedObject(self, @selector(nickName), value, OBJC_ASSOCIATION_COPY_NONATOMIC);
    }


    @end

  • 相关阅读:
    javaScript:制作随机验证码
    XSL简明教程
    javascript判断用户使用的浏览器
    jswindow对象的方法和属性资料
    VBscript操作文件
    终于找到组织了...
    公司网站的物流费用设计
    配置live Writer来发blog
    IIS必备的2个插件
    全国默哀 网站首页都要变成灰色的简单解决办法
  • 原文地址:https://www.cnblogs.com/zhangleixy/p/5082805.html
Copyright © 2011-2022 走看看