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

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

问题描述

我有一种情况,似乎我需要添加实例变量到一个类别,但我知道从苹果的文档,我不能这样做。所以我想知道什么最好的替代或解决方法是。

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天全站免登陆