博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
iOS 运行时添加属性和方法
阅读量:4506 次
发布时间:2019-06-08

本文共 1215 字,大约阅读时间需要 4 分钟。

第一种:runtime.h里的方法
BOOL class_addProperty(Class cls, const char *name, const objc_property_attribute_t *attributes, unsigned int attributeCount)
#include 
#import
@interface SomeClass : NSObject { NSString *_privateName; } @end @implementation SomeClass - (id)init { self = [super init]; if (self) _privateName = @"Steve"; return self; } @end NSString *nameGetter(id self, SEL _cmd) { Ivar ivar = class_getInstanceVariable([SomeClass class], "_privateName"); return object_getIvar(self, ivar); } void nameSetter(id self, SEL _cmd, NSString *newName) { Ivar ivar = class_getInstanceVariable([SomeClass class], "_privateName"); id oldName = object_getIvar(self, ivar); if (oldName != newName) object_setIvar(self, ivar, [newName copy]); } int main(void) { @autoreleasepool { objc_property_attribute_t type = { "T", "@\"NSString\"" }; objc_property_attribute_t ownership = { "C", "" }; // C = copy objc_property_attribute_t backingivar = { "V", "_privateName" }; objc_property_attribute_t attrs[] = { type, ownership, backingivar }; class_addProperty([SomeClass class], "name", attrs, 3); class_addMethod([SomeClass class], @selector

转载于:https://www.cnblogs.com/developer-ios/p/5077880.html

你可能感兴趣的文章
排序算法之归并排序(Merge Sort)
查看>>
libevent学习七(bufferevent)
查看>>
[BZOJ1603] [Usaco2008 Oct] 打谷机
查看>>
sublime-text3打造markdown编辑器
查看>>
how to install flash
查看>>
使用Callable、Future以及FutureTask进行线程操作
查看>>
LiberOJ#6178. 「美团 CodeM 初赛 Round B」景区路线规划 概率DP
查看>>
记一次微信支付走过的坑
查看>>
poj1273 Drainage Ditches 基础网络流
查看>>
iOS开发 私有变量 私有属性的使用选择
查看>>
hibernate.properties和hibernate.cfg.xml
查看>>
Hive任务优化--控制hive任务中的map数和reduce数
查看>>
mongodb添加管理员密码
查看>>
Django 之单个mysql表使用
查看>>
Enviroment for Oracle_home& Path
查看>>
IIS默认网址
查看>>
Arduino基本函数介绍
查看>>
Keil C51 的printf
查看>>
关于指针
查看>>
C 語言中的 sprintf() 函數
查看>>