如何使用Objective-C类别 [英] How to Use Objective-C Categories

查看:149
本文介绍了如何使用Objective-C类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您在文件中实现类的类别时,默认情况下该类的所有实例都属于该类别吗?

When you implement a category of a class in a file, will all the instances of that class be of the category by default?

我是Objective的新手-C我试图使我的不可编辑的UITextView不可选。我使用以下类别找到了这个答案:
https://stackoverflow.com/a/8013538/1533240

I'm new to Objective-C and I'm trying to make my uneditable UITextView non-selectable. I came across this answer using a category: https://stackoverflow.com/a/8013538/1533240

具有以下解决方案:

@implementation UITextView (DisableCopyPaste)

-(BOOL) canBecomeFirstResponder
{
    return NO;
}
@end

我在代码中添加了代码段,但它似乎没有工作,我仍然可以选择文本。我通常声明 UITextView

I added the snippet to my code, but it doesn't seem to be working in that I can still select the text. My declaration of the UITextView is the usual:

titleLabel = [[UITextView alloc] initWithFrame:frame];

我尝试将声明更改为 [DisableCopyPaste alloc] 但这似乎没有用..哈哈。

I tried changing the declaration to [DisableCopyPaste alloc] but that didn't seem to work.. haha.

谢谢!

推荐答案

你误解了类别的要点。类别将方法添加到现有类。它们绝不能用于覆盖现有方法。这样做是未定义的行为(技术上仅在一种情况下未定义,但您无法预测这种情况,因此您必须假设它适用)。

You misunderstand the point of categories. Categories add methods to an existing class. They must never be used to override existing methods. Doing so is undefined behavior (technically only undefined in one case, but you can't predict that case, so you must assume it applies).

如果您需要覆盖方法,你必须子类,而不是使用类别。请参阅您关联的问题的最佳答案。

If you need to override methods, you must subclass, not use categories. See the top answer to the question you linked.

这篇关于如何使用Objective-C类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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