zoukankan      html  css  js  c++  java
  • iOS类别(Category)和扩展(Extension,匿名类)

    Category在iOS在开发常用。

    特别是对于系统扩展上课时间。我们不能继承系统类。直接添加到系统类方法,最大程度上体现Objective-C动态语言特征。

    #import
    @interface NSObject (Category)
    - (void)myMethod;
    @end

    这是一个最简单的Category,作用于NSObject类。给NSObject加入了一个方法。


    使用Category须要注意的点:
    (1) Category的方法不一定非要在@implementation中实现。也能够在其它位置实现,可是当调用Category的方法时,根据继承树没有找到该方法的实现,程序则会崩溃。


    (2) Category理论上不能加入变量,可是能够使用@dynamic 来弥补这样的不足。

    #import
    static const void * externVariableKey =&externVariableKey;
    @implementation NSObject (Category)
    @dynamic variable。
    - (id) variable
    {
           return objc_getAssociatedObject(self, externVariableKey);
    }
    - (void)setVariable:(id) variable
    {
        objc_setAssociatedObject(self, externVariableKey, variable, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    } 

    -----------------------------------------------------------

    Extension很像是没有命名的类别,即匿名类别

    @interface MyClass : NSObject 
    @property (retain, readonly) float value; 
    @end 
    //一般的时候。Extension都是放在.m文件里@implementation的上方。
    @interface MyClass () 
    @property (retain, readwrite) float value; 
    @end


    使用Extension须要注意的点:
    (1) Extension中的方法必须在@implementation中实现,否则编译会报错。


    两者有一点差别


    图片摘自: http://blog.sina.com.cn/s/blog_a2c098b50101gsn0.html

    版权声明:本文博客原创文章。博客,未经同意,不得转载。

  • 相关阅读:
    继承
    面向对象_封装练习
    ajax分页与组合查询配合使用
    Linq的分页与组合查询的配合使用
    发送邮件和数据导出
    GridView的使用
    母版页的使用
    DIV+CSS命名规范
    Ajax基础
    jQuery动画效果
  • 原文地址:https://www.cnblogs.com/mfrbuaa/p/4642925.html
Copyright © 2011-2022 走看看