有什么方法可以猴子补丁或混淆NSArray(或其他类集群)吗? [英] Is there any way to monkey-patch or swizzle an NSArray (or other Class Cluster)?

查看:151
本文介绍了有什么方法可以猴子补丁或混淆NSArray(或其他类集群)吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,我正在一个项目中,我想为 NSArray 的所有实例别名另一种方法,并且认为这不会太困难并带有很好的老式方法。

Today I was working on a project in which I wanted to "alias" an alternative method for all instances of NSArray, and didn't think it would be too difficult with some good old-fashioned method swizzling.

我爆发了 JRSwizzle 和…

[NSArray jr_swizzleMethod:@selector(objectAtIndex :) withMethod:@selector(objectAtIndex_accordingToMe :) error:nil];

要清楚,我将其与 NSArray 上的相应类别配对,这是一个名为 objectAtIndex_accordingToMe的实例方法:

To be clear, I paired this with the appropriate category on NSArray, an instance method called objectAtIndex_accordingToMe:.

但是,我只是在相同的旧索引下获得了相同的旧对象。叹。最终,我发现尽管没有抛出任何错误-我由于 NSArray 是一个类集群

However, I was just getting that same old object, at that same old index. Sigh. Ultimately, I figured out that despite not throwing any errors - I'm not going to achieve these results due to the fact that NSArray is a class cluster

我想我的问题更多是不愿意接受这个确实尝试覆盖 NSArray 方法的尽头。我的意思是,这是 NSArray ..人们必须想弄清楚它,不是吗?一个人会认为,苹果的基础课程将成为遍地开花的人的主要目标!

I guess my question is more of an unwillingness to accept that "this" is really the end of the road trying to override NSArray methods. I mean, come on this is NSArray.. people must wanna muck around with it, no? One would think that Apple's foundation classes would be a prime target for swizzlers, everywhere!

因此,有一种方法可以更改,别名, monkey-patch ,覆盖或以其他方式使用…NSArray等(无子类化)?

So, is there a way to alter, alias, monkey-patch, override, or otherwise have your way with… an NSArray, etc. (without subclassing)?

推荐答案

大概您有一个需要此行为的特定数组。不管它是什么,都可以获取该实例的类对象,并轻松对其进行处理:

Presumably you have a particular array for which you'd like this behavior. You can get that instance's class object, no matter what it is, and swizzle that quite easily:

[[myArray class] jr_swizzleMethod:@selector(objectAtIndex:) withMethod:@selector(objectAtIndex_accordingToMe:) error:nil];

也只有少数几个 NSArray :

NSArray * trees = [NSArray array];
NSArray * birds = [NSArray arrayWithObjects:@"Albatross", @"Budgerigar", @"Cardinal", nil];
NSMutableArray * dogs = [NSMutableArray arrayWithObjects:@"Airedale", @"Beagle", @"Collie", nil];

NSLog(@"%@ %@ %@", [trees class], [birds class], [dogs class]);

前两个我们得到 __ NSArrayI __ NSArrayM 第三,所以可能(这是非常易碎),您可以使用运行时函数来捕获类对象名称:

We get __NSArrayI for the first two and __NSArrayM for the third, so potentially (this is very fragile) you could use a runtime function to grab the class object by name:

[objc_getClass("__NSArrayI") jr_swizzleMethod:@selector(objectAtIndex:) withMethod:@selector(objectAtIndex_accordingToMe:) error:nil];

这篇关于有什么方法可以猴子补丁或混淆NSArray(或其他类集群)吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆