如何用runtime In Objective-C改变成员变量的值?

How to change the value of the member variables with runtime In Objective-C?

我有一个 tableView,我希望它的 contentInsets 始终为零。所以我添加代码:

class_replaceMethod([UITableView class], @selector(setContentInset:), (IMP)setContentInsetZero, "@");

然后我编写 setContentInsetsZero 函数:

void setContentInsetZero(id SELF, SEL _cmd, UIEdgeInsets insets) {

    Ivar tableViewInsets = class_getInstanceVariable([UITableView class], "_contentInset");

    object_setIvar(SELF, tableViewInsets, [NSValue valueWithUIEdgeInsets:UIEdgeInsetsZero]);

} 

程序在运行的时候调用了setContentInsetZero函数,但是没有用?谁能告诉我为什么?

您可以通过更进一步的方法 swizzling 来完成您想要做的事情。将您的新方法视为包装器而不是替代品,它可以拦截参数并调用原始方法。

查看此 link 以了解执行所需操作的确切方法:http://nshipster.com/method-swizzling/

这将影响您应用程序中的所有 UITableView,更好的解决方案可能是子类化 UITableView 并重写该方法(使用超级调用传递替换参数)。然后你就可以在需要的地方使用它了。