类扩展与分类

来源:互联网 发布:动物知乎 编辑:程序博客网 时间:2024/05/19 18:12

类扩展与分类


创建日期:2016.5.12


类扩展可以添加 方法与属性
下面为UIView的类扩展

@interface UIView(UIViewHierarchy)@property(nullable, nonatomic,readonly) UIView       *superview;@property(nonatomic,readonly,copy) NSArray<__kindof UIView *> *subviews;@property(nullable, nonatomic,readonly) UIWindow     *window;- (void)removeFromSuperview;- (void)insertSubview:(UIView *)view atIndex:(NSInteger)index;- (void)exchangeSubviewAtIndex:(NSInteger)index1 withSubviewAtIndex:(NSInteger)index2;

但类扩展声明的方法一定要在@implementation实现

分类只能添加 方法

在XCODE中可以通过 NEW FILE… ->Objective-C File中创建分类或类扩展

创建出的分类:
NSString+name.h
NSString+name.m
创建出的类扩展:
NSString_name.h

由此可以看出来分类与扩展的区别
类扩展默认只有.h文件,一般用于给类中添加属性
而分类一般用于给类添加方法


  1. 类扩展常见用法一
    这种写法可以在.h中声明多个@interface将类的功能模块化
#import <UIKit/UIKit.h>@interface XMEIZIViewController : UIViewController@property (weak, nonatomic) IBOutlet UICollectionView *CollectionView;@end@interface XMEIZIViewController (ex)@property (nonatomic,strong)NSString *name;@end

2.类扩展常见用法二

在.m文件中添加匿名类扩展
类扩展中可以申明类的私有属性及方法

@interface XMEIZIViewController ()@end@implementation XMEIZIViewController@end
0 0
原创粉丝点击