---
title: "objective c的runtime特性"
author: "tonynju"
date: "2012-08-25T18:28:14Z"
tags: []
categories: ["编程语言"]
slug: "objective-c-runtime"
draft: false
lastmod: "2012-08-25T18:28:14Z"
id: 1662923
url: "https://tonynju.iteye.com/blog/1662923"
---

使用objective c的runtime特性动态增加字段。

在category中特别有用，可以实现在不增加变量的情况下达到成员变量类似的效果。

示例：

\- (BOOL)isRobot {

 

  NSNumber \*boolNum = objc\_getAssociatedObject(self, kPlayerIsRobotKey);

  if (boolNum == nil) {

    return NO;

  } else {

    return \[boolNum boolValue];

  }

}

 

\- (void)setIsRobot:(BOOL)isRobot {

 

  objc\_setAssociatedObject(self, kPlayerIsRobotKey, \[NSNumber numberWithBool:isRobot], OBJC\_ASSOCIATION\_RETAIN\_NONATOMIC);

}