zoukankan      html  css  js  c++  java
  • Objective

    前面我们基本认识了类别是用来怎么用的, 那么现在我们来讲讲在实际开发中的一些事项, 其实在实际开发中, 类别用的最多的是给系统类添加方法的, 因为我们自己自定义的类灵活性比系统类要高, 而系统的类是固定死的, 如果给它添加方法, 我们只能选择使用类别, 下面让我们来看看~~


    例子:

    #import <Foundation/Foundaiton.h>
    
    @interface NSString (Number)
    
    @end
    
    @implementation NSString (Number)
    
    @end
    
    int main()
    {
    
        return 0;
    }

    上面就是我们给系统类NSString另外添加的方法, 现在我们有一个需求, 我要求, 设计一个类方法, 在输入的字符串, 要把里面的阿拉伯数字个数打印出来, 那么怎么添加呢?



    下面让我们一起来看看:

    #import <Foundation/Foundaiton.h>
    
    @interface NSString (Number)
    + (int)numberCountOfString:(NSString *)string;
    @end
    
    @implementation NSString (Number)
    + (int)numberCountOfString:(NSString *)string
    {
        int count = 0;
        for (int i = 0; i <= string.lenth; i++)
        {
    	unichar c = [string characterAtIndex:i];
    
    	if (i = '0' && i = '9')
    	{
       	    count++;
    	} 
        }
        return count;
    }
    
    @end
    
    int main()
    {
        int count = [NSString numberCountOfString:@"asdsa1231asd33123"];
        NSLog(@"%d", count);
        return 0;
    }

    这样子就可以完成我们所需的结果啦~~~那如果我们要的是对象方法呢?? 我们下面继续来看看~~

    #import <Foundation/Foundaiton.h>
    
    @interface NSString (Number)
    - (int)numberCount
    @end
    
    @implementation NSString (Number)
    - (int)numberCount
    {
        int count = 0;
        for (int i = 0; i < self.lenth; i++)
        {
    	unichar c = [self characterAtIndex:i];
    
    	if (i = '0' && i = '9')
    	{
    	    count++;
    	} 
        }
        return count;
    }
    
    @end
    
    int main()
    {
        int count = [@"oweq123oqwei94hsd1" numberCount];
        NSLog(@"%d", count);
        return 0;
    }

    好了, 对象方法也出来了, 从上面的例子上看, 貌似对象方法更加的简单~~这个就是个人设计的问题了, 哪个方法简单, 我们就用哪个方法, 这个是我们一直推荐的思想.





    好了, 这次我们就到这里了, 下次我们继续~~~


  • 相关阅读:
    [考试反思]0421省选模拟76:学傻
    [考试反思]0420省选模拟75:安在
    [考试反思]0418省选模拟74:杂枝
    [考试反思]0417省选模拟73:纠结
    [考试反思]0416省选模拟72:停滞
    [考试反思]0415省选模拟71:限制
    [考试反思]0414省选模拟70:阻塞
    [考试反思]0413省选模拟69:遗弃
    [考试反思]0411省选模拟68:毒瘤
    [考试反思]0410省选模拟67:迷惑
  • 原文地址:https://www.cnblogs.com/iOSCain/p/4282836.html
Copyright © 2011-2022 走看看