zoukankan      html  css  js  c++  java
  • Objective-C 之category

    参考资料:iOS设计模式——Category

    Category

    • Category模式用于向已经存在的类添加方法从而达到扩展已有类的目的。
    • 相当于Swift中的功能扩展(extension)。
    • 新添加的方法同样也会被被扩展的类的所有子类自动继承。

    Category的用途

    1、 在不创建继承类的情况下实现对已有类的扩展。
    2、 简化类的开发工作(当一个类需要多个程序员协同开发的时候,Category可以将同一个类根据用途分别放在不同的源文件中,从而便于程序员独立开发相应的方法集合)。
    3、将常用的相关的方法分组。
    4、 在没有源代码的情况下可以用来修复BUG。

    示例:

    在项目中添加文件选着Category文件类型


    Objective-C-Category.jpg

    NSString+EndWith.h

    
    #import <Foundation/Foundation.h>
    
    @interface NSString (EndWith)
    -(BOOL)endWith:(NSString*)end;
    
    @end
    
    

    NSString+EndWith.m

    #import "NSString+EndWith.h"
    
    @implementation NSString (EndWith)
    -(BOOL)endWith:(NSString *)end{
        NSString *selfEnd = [self substringFromIndex:[self length]-[end length]];
        return [selfEnd isEqualToString:end];
    }
    
    @end
    
    

    main.m

    #import <Foundation/Foundation.h>
    #import "NSString+EndWith.h"
    int main(int argc, const char * argv[]) {
        @autoreleasepool {
            
            NSString * str = @"c:/Media/mp3/xxx.mp3";
            NSLog(@"%d",[str endWith:@".mp3"]);
        }
        return 0;
    }
    
  • 相关阅读:
    005 HTML+CSS(Class027
    004 HTML+CSS(Class024
    003 HTML+CSS(Class011
    002HTML+CSS(class007-010)
    001HTML+CSS(class001-006)
    021 vue路由vue-router
    020 Vue 脚手架CLI的使用
    019 Vue webpack的使用
    018 vue的watch属性
    017 vue的插槽的使用
  • 原文地址:https://www.cnblogs.com/Free-Thinker/p/10797416.html
Copyright © 2011-2022 走看看