类别而不是继承的实际用途是什么? [英] What is the actual use of categories instead of inheritance?

查看:38
本文介绍了类别而不是继承的实际用途是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解类别的实际用法,而不是Objective-C中的继承.我什么时候应该使用类别?一个带有代码的真实示例将很有帮助.

I'm trying to understand the actual use of categories as opposed to inheritance in Objective-C. When should I prefer to use a category? A real-life example with code would be helpful.

推荐答案

当我需要将一些方便的函数添加到现有类中而又不需要子类来覆盖该类的某些现有函数时,我使用了类别班级.

I used categories when I need to add some convenient functions that I will use repeatedly to the existing class without having a need to subclass to overwrite some existing functions of that class.

例如,当我想检查一个空字符串,或删除一个字符串的所有前导和尾随空格时:

For example, when I want to check for an empty string, or remove all leading and trailing spaces of a string:

.h文件:

@interface NSString  (Extension)

-(BOOL)isEmptyString;
-(NSString *)trimLeadingAndTrailingWhiteSpaces;

@end

.m文件:

@implementation NSString  (Extension)

-(BOOL)isEmptyString
{
    NSString *myString = [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if (myString.length == 0)
        return TRUE;
    else
       return FALSE;
}

-(NSString *)trimLeadingAndTrailingWhiteSpaces
{
    NSString *myString = [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    return myString;
}
@end

要使用它:

 someString = [someString trimLeadingAndTrailingWhiteSpaces];

 if ([someString isEmptyString])
       {
         //someString is empty, do whatever!
       }

这篇关于类别而不是继承的实际用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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