iOS class_addMethod使用

iOS runtime 通过class_addMethod在本类中给其他类添加方法 本类.m文件: #import "ViewController.h" #import "AViewController.h" #import @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do 阅读详情

前言

近期项目不急,有时间看一些自己想看的东西。记得面试的时候都是在问runtimer的知识点,自己虽然知道一点这里面的知识点,但是很零碎。所以在这几天好好的研究一下。其实我也问过一个做sdk的朋友,他也说基本上平时开发用的不是很多。做sdk的用的比较多,因为要获取开发人员的某些属性,或者在不知道开发人员的类的结构下添加方法等。本次说class_addMethod 这个很有用的方法,感觉他就是一个作弊器。

正文

/** 
 * Adds a new method to a class with a given name and implementation.
 * 
 * @param cls The class to which to add a method.
 * @param name A selector that specifies the name of the method being added.
 * @param imp A function which is the implementation of the new method. The function must take at least two arguments—self and _cmd.
 * @param types An array of characters that describe the types of the arguments to the method. 
 * 
 * @return YES if the method was added successfully, otherwise NO 
 *  (for example, the class already contains a method implementation with that name).
 *
 * @note class_addMethod will add an override of a superclass's implementation, 
 *  but will not replace an existing implementation in this class. 
 *  To change an existing implementation, use method_setImplementation.
 */
OBJC_EXPORT BOOL class_addMethod(Class cls, SEL name, IMP imp, 
                                 const char *types) 
     __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0);

这个是API文档的解释,基本就是说这可以加入新的方法到一个类里面,然后介绍这里面几个参数的作用之类的。我感觉无论什么都要自己亲身实践才行,所以直接先上代码:

- (void)viewDidLoad {
    [super viewDidLoad];

   //动态添加一个方法
    Person *p = [[Person alloc]init];
    class_addMethod([Person class], @selector(printPerson), class_getMethodImplementation([ViewController class], @selector(find)), "v@:");
    [p performSelector:@selector(printPerson)];
}

非常简单的代码片段,我有一个Person类,现在我要在运行的时候给他增加一个方法,并且调用这个方法。

 class_addMethod(Class cls, SEL name, IMP imp, 
                                 const char *types)

首先我们看看这个方法里面的参数:
Class cos:我们需要一个class,比如我的[Person class]。
SEL name:这个很有意思,这个名字自己可以随意想,就是添加的方法在本类里面叫做的名字,但是方法的格式一定要和你需要添加的方法的格式一样,比如有无参数。
IMP imp:IMP就是Implementation的缩写,它是指向一个方法实现的指针,每一个方法都有一个对应的IMP。这里需要的是IMP,所以你不能直接写方法,需要用到一个方法:

OBJC_EXPORT IMP class_getMethodImplementation(Class cls, SEL name) 
     __OSX_AVAILABLE_STARTING(__MAC_10_5, __IPHONE_2_0);

这个方法也是runtime的方法,就是获得对应的方法的指针,也就是IMP。
const char *types:这一个也很有意思,我刚开始也很费解,结果看了好多人的解释我释然了,知道吗,我释然啦,����。这个东西其实也很好理解:
比如:”v@:”意思就是这已是一个void类型的方法,没有参数传入。
再比如 “i@:”就是说这是一个int类型的方法,没有参数传入。
再再比如”i@:@”就是说这是一个int类型的方法,又一个参数传入。
好了,参数解释完了,还有一点需要注意,用这个方法添加的方法是无法直接调用的,必须用performSelector:调用。为甚么呢???
因为performSelector是运行时系统负责去找方法的,在编译时候不做任何校验;如果直接调用编译是会自动校验。
知道为甚么了吧,你添加方法是在运行时添加的,你在编译的时候还没有这个本类方法,所以当然不行啦。

结束

啦啦啦,结束啦,代码示例在此,如果您觉得还可以,给个✨✨吧。

iOS Runntime 动态添加类方法并调用-class_addMethod 主要介绍了iOS Runntime 动态添加类方法并调用-class_addMethod的相关资料,非常不错,具有参考借鉴价值,需要的朋友可以参考下 立即下载

相关推荐

Ansys Zemax|无焦系统设计中的角度单位优化技巧

本文详细介绍了在Ansys Zemax OpticStudio中进行无焦系统设计的核心技巧。重点阐述了从聚焦思维到角度思维的转换,并演示了如何通过开启‘无焦像空间’模式、构建以波前和光束尺寸为目标的评价函数来优化激光扩束镜等系统。文章还分享了使用IMSF操作数处理混合系统以及常见误区避坑的实用指南,旨在帮助光学设计者高效完成无焦系统的设计与分析。

weixin_29231027的博客 366

iOS-Runtime之class_addMethod给类动态添加方法

一、简介 /** * Adds a new method to a class with a given name and implementation. * * @param cls The class to which to add a method. * @param name A selector that specifies the name of the method being added. * @param imp A function which is the imple

MinggeQingchun的博客 1753

新手学习Vivado XDMA (1) - 配置详细分析

PCIe 在 Vivado XDMA 中的配置分析。

qq_18553915的博客 9712

iOS用runtime给一个类动态添加方法 ---class_addMethod

先介绍下class_addMethod这个fangfa /** * Adds a new method to a class with a given name and implementation. * * @param cls The class to which to add a method. * @param name A selector that specifies t

gunmm的博客 6842

AutoSAR RTE调度机制揭秘:从定时器事件到Runnable执行的完整流程

本文深入解析了AutoSAR RTE(运行时环境)的核心调度机制,详细阐述了从定时器事件触发到Runnable(可运行实体)执行的完整流程。通过剖析Rte_Start()函数、OS任务与警报的交互,以及事件驱动循环,揭示了RTE如何作为幕后指挥家,高效、可靠地协调软件组件间的周期性任务执行,是打通AutoSAR应用开发的关键。

weixin_29169899的博客 230

Himall商城ExpressDaDaHelper 取消订单(线上环境)

Himall商城ExpressDaDaHelper 取消订单(线上环境)

GZM888888的博客 401

iOS类添加方法、属性学习笔记

一、在运行时为类添加方法我们首先定义了一个EmptyClass,继承NSObject,没有任何自带方法,接着定义了一个函数。这里提一句,Obj-C的方法(method)就是一个至少需要两个参数(self,_cmd)的C函数,这个函数仅仅输出一句Hello。接下来在addMethod方法中,我们调用class_addMethod()为EmptyClass添加方法,class_addMethod()是这

沐风 1308

SDMA 如何实现设备对主机内存的访问

摘要:SDMA(System Direct Memory Access)是PCIe设备直接访问主机内存的核心机制,使外设无需CPU干预即可高效读写系统RAM。其实现原理包括:设备作为主控发起DMA请求,通过PCIe Memory TLP访问主机物理地址;完整通路涉及驱动分配DMA安全内存、设备配置、地址转换(IOMMU)和中断通知等步骤;关键技术涵盖地址类型(HPA/IOVA)、TLP格式、缓存一致性和安全防护机制。SDMA广泛应用于GPU、网卡、NVMe等高性能场景,是现代异构计算的基础技术,需软硬件协同

MHD0815的博客 240

iOS使用 class_addMethod hook 类的方法

oc runtime 实现交换方法方案二class_addMethodclass_replaceMethod # 方案一 直接使用 method_exchangeImplementations 交换两个方法的实现 该方案可以实现方法的替换,但是有风险, 就是如果是在子类实现了交换方法,但是交换的是一个父类实现了子类没有实现的方法,就会将父类方法的替换成子类的实现,如果父类的实例对象调用父类的方法的时候,由于已经替换成子类实现的方法,就会因为父类没有实现该方法导致崩溃 如; @interface Father

liubo的博客 957

Python之abbrobotegm包语法、参数和实际应用案例

`abbrobotegm` 是用于控制 ABB 机器人的 Python 接口包,主要通过 EGM(Externally Guided Motion,外部引导运动)协议与 ABB 机器人控制器进行通信,实现对机器人的实时位置控制、状态监控和运动引导等功能。该包适用于需要将 ABB 机器人与外部系统(如视觉系统、传感器等)集成的场景。

王国平的博客 1255

RK3568平台(KBuild篇)KBuild编译体系

从Linux内核2.6开始,Linux内核的编译采用Kbuild系统,这和过去的编译系统有很大的不同,尤其对于Linux内核模块的编译。在新的系统下,Linux编译系统会两次扫描Linux的Makefile:首先编译系统会读取Linux内核顶层的Makefile,然后根据读到的内容第二次读取Kbuild的Makefile来编译Linux内核。kbuild,即 kernel build,用于编译 Linux 内核文件。

weixin_49303682的博客 349

利用RunTime Hook 实现iOS防止按钮连续响应点击

虽然iOS很少出现这种问题, 而且也有很多办法可以解决. 为了更好的熟悉了解RunTime, 那我们就来看看用RunTime是这么解决的吧. 链接:https://github.com/ConnorForGIT/JCButton 下面是部分代码.     static dispatch_once_t onceToken; dispatch_onc

u012868863的博客 1644

TIA protal与SCL从入门到精通(4)——软件单元使用

平台: TIA portal 15.1 1.添加软件单元 添加软件单元如下图: 关于软件单元使用基本限制,看如下文章即可 TIA protal与SCL从入门到精通(3)——软件单元基本介绍 每个软件单元是一个独立结构,所以每个软件单元的运行方式与实际PLC类似,所以首先添加主函数块: 注意:无论系统是否是具有并发性(这里不要混淆并行与并发的概念),在PLC所有主函数执行总是按主函数依次完成...

苦走一口田 7380

iOS高级开发~Runtime四部曲(四)

iOS高级开发~Runtime(一)  iOS高级开发~Runtime(二)  iOS高级开发~Runtime(三)  iOS高级开发~Runtime(四) 用C代替OC: #import  #import  #import  extern int UIApplicationMain (int argc,char *argv[],

CQAHF的博客 383

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

RunTime(消息机制) + RunTime(消息转发)

一.消息机制 1.在viewDidLoad中直接用 performSelector:@selector(doSomething) 来调用doSomething方法时,会发现找不到这个方法而奔溃.此时,我们可以在resolveInsantanceMethod:(SEL)...

weixin_30532759的博客 70

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

class_addMethod的详解

Obj-C用起来真是各种happy,比如现在有这样一种情况:有一个类,我们希望它能响应一个消息(message),但是这个类没有相应的方法(method),而你又偏偏不能重写/继承这个类。这时我们可能会想到,能不能动态地给类添加一个方法呢?感谢Obj-C,仅需简单几步就能实现。 先看一段代码 #if TARGET_IPHONE_SIMULATOR #import #else #imp

lvmaker的专栏 2万+

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

Delphi IOS class_addMethod

class_addMethod    学习FMX.Platform.iOS.pas文件的处理办法 d:\program files (x86)\embarcadero\studio\17.0\source\fmx\FMX.Platform.iOS.pas performFetchWithCompletionHandler procedure performFetchWithComple...

weixin_33779515的博客 105

Runtime objc4-779.1 OC中,为什么swizzleMethod时要先addMethod?

我们swizzleMethod的方法通常如下 void swizzleMethod(Class class, SEL originalSelector, SEL swizzledSelector) { Method originalMethod = class_getInstanceMethod(class, originalSelector); Method swizzledMe...

王学森的专栏 668

Runtime基础使用场景-拦截替换方法(class_addMethod ,class_replaceMethod和method_exchangeImplementations)

前话 这几天在系统的学习 runtime,在学习 runtime 的基础使用案例中,"方法替换"这种使用情况下,发现有两种写法. 其实也不是两种写法,准确的来说一种是比较严谨的,另一种则没有那么严谨. 发现这两种写法的差异后,我主要集中在下列: class_addMethodclass_replaceMethodmethod_exchangeImplementations

fishmai的专栏 5332

说说objcRuntime的一些妙用(class_addMethod,class_replaceMethod)

前言:陈列一下今天要讲的知识点:class_addMethod,class_replaceMethod,method_getImplementation,object_getClass 涉及到的知识 》》使用category,通过Runtime实现用自己的函数调换掉原生函数 》》oc的message forwarding 》》使用Runtime为类添加原来没有的方法

iOS 技术支持 2520

iOS开发 Method Swizzling黑魔法处理异常问题

class_addMethod如果类没有该方法,为其添加方法,则返回YES;如果有该方法,则返回NO,所以我们在交互前可以加入这个进行判断。} else {防止出现问题,防止直接替换的时候调用过程中出现unrecognized selector sent to instance的崩溃问题。

一名开发者 1250

ios动态创建类Class

【Objective-C Runtime动态加载】---动态创建类Class 动态创建类Class,动态添加Class成员变量与成员函数,动态变量赋值与取值,动态函数调用等方法 a.使用objc_allocateClassPair创建一个类Class const char * className = "Calculator"; Class kclass = objc_g...

weixin_34054931的博客 227

iOS Sharing #02 | 2019-03-30

目录 1、类方法去哪里找? 2、isa指针有几种类型么? 3、分类的方法具体是在什么时候添加到类的方法列表中? 4、class_addMethod()都需要什么参数? 5、iOS消息转发流程 1、类方法去哪里找? 答: 见上一期《iOS Sharing #01 | 2019-03-23》第5问 5、实例方法去哪里找? 2、isa指针有几种类型么? 答: isa指针分,指针类型和非指针类型,32...

weixin_34244102的博客 105

iOS开发-底层篇-Class详解,ios底层-class详解

前言:iOS的开发语言objective-c,它的真实面目是它不是真正的面向对象语言,而抽象理解为此而已。其实它就是C+,有个公式可以很好地诠释那就是 OC = C + Runtime; 接下来我们就好好讲讲在Runtime下的objc-class。准备资料,objc4-646/runtime。 一:Class定义     1.1 小小说明一下objc-api.h里的OBJC_I

巴拉巴拉小魔仙 956

[底层原理]iOS中函数的类型编码

建了一个面试题解答的项目,大家可以看一看,希望大家帮忙给一个star,谢谢了! 项目地址:https://github.com/NotFound9/interviewGuide 起因 最近在复习iOS中的消息转发机制,如果需要在动态方法解析这一阶段对消息进行处理,一般需要调用class_addMethod方法给类动态地增加方法,例如: 我当时敲代码的时候发现自己对于cl...

ruiwen125的博客 338
上一篇: 关闭一些运行警告
下一篇: 关于performSelector调用和直接调用区别
猿人在北京
博客等级 码龄11年 92粉丝 94原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值