目标 C 类别的实例变量 [英] Instance Variables for Objective C Categories

查看:20
本文介绍了目标 C 类别的实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的情况似乎需要向类别添加实例变量,但我从 Apple 的文档中知道我不能这样做.所以我想知道最好的替代方案或解决方法是什么.

I have a situation where it seems like I need to add instance variables to a category, but I know from Apple's docs that I can't do that. So I'm wondering what the best alternative or workaround is.

我想要做的是添加一个类别,为 UIViewControllers 添加功能.我会发现它在我所有不同的 UIViewControllers 中都很有用,无论它们扩展什么特定的 UIViewController 子类,所以我认为一个类别是最好的解决方案.为了实现这个功能,我需要几个不同的方法,我需要跟踪它们之间的数据,所以这就是我想要创建实例方法的原因.

What I want to do is add a category that adds functionality to UIViewControllers. I would find it useful in all my different UIViewControllers, no matter what specific UIViewController subclass they extend, so I think a category is the best solution. To implement this functionality, I need several different methods, and I need to track data in between them, so that's what led me to wanting to create instance methods.

如果它有帮助,这就是我特别想做的事情.我想让软件键盘何时隐藏和显示更容易跟踪,以便我可以在我的视图中调整内容的大小.我发现可靠地做到这一点的唯一方法是将代码放在四个不同的 UIViewController 方法中,并在实例变量中跟踪额外的数据.所以这些方法和实例变量是我想放在一个类别中的,所以我不必每次需要处理软键盘时都复制粘贴它们.(如果对于这个确切的问题有更简单的解决方案,那也很好——但我仍然想知道类别实例变量的答案以供将来参考!)

In case it's helpful, here's what I specifically want to do. I want to make it easier to track when the software keyboard hides and shows, so that I can resize content in my view. I've found that the only way to do it reliably is to put code in four different UIViewController methods, and track extra data in instance variables. So those methods and instance variables are what I'd like to put into a category, so I don't have to copy-paste them each time I need to handle the software keyboard. (If there's a simpler solution for this exact problem, that's fine too--but I would still like to know the answer to category instance variables for future reference!)

推荐答案

是的,您可以这样做,但是既然您要问,我就必须问:您绝对确定需要这样做吗?(如果你说是",然后回去,弄清楚你想做什么,看看是否有不同的方式去做)

Yes you can do this, but since you're asking, I have to ask: Are you absolutely sure that you need to? (If you say "yes", then go back, figure out what you want to do, and see if there's a different way to do it)

但是,如果您真的想将存储注入到您无法控制的类中,请使用 关联参考.

However, if you really want to inject storage into a class you don't control, use an associative reference.

这篇关于目标 C 类别的实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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