协议与分类--27:Class-continuation分类隐藏实现细节

Class-continuation分类

  • Class-continuation分类和普通的分类不同,它必须定义在其所接续的那个类的实现文件中

  • 此分类可以声明属性,且此分类没有特定的是现实文件,其中方法都定义在主实现文件中

  • 一般存放不需要对外公开的属性(例子中的age)

#import <Foundation/Foundation.h>
@interface Person : NSObject
@property (nonatomic,copy,readonly) NSString *firstName;
@property (nonatomic,copy,readonly) NSString *lastName;
@property (nonatomic,strong,readonly) NSArray *friends;
- (instancetype)initWithFristName:(NSString *)firstName withLastName:(NSString *)lastName;
@end


--------------------
#import "Person.h"
@interface Person()
@property (nonatomic,assign) NSInteger age;
@property (nonatomic,strong,readwrite) NSArray *friends;
@end
@implementation Person
- (instancetype)initWithFristName:(NSString *)firstName withLastName:(NSString *)lastName{
    self = [super init];
    if (self) {
        _firstName = firstName;
        _lastName = lastName;
    }
    return self;
}
@end
  • 如果某属性在主接口中声明为“只读”,而类内部要用setter方法修改此属性,那么就在Class-continuation分类中将其扩展为“readwrite”(例子中的friends)
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property (nonatomic,copy,readonly) NSString *firstName;
@property (nonatomic,copy,readonly) NSString *lastName;
@property (nonatomic,strong,readonly) NSArray *friends;

- (instancetype)initWithFristName:(NSString *)firstName withLastName:(NSString *)lastName;
@end

-------------------------------
#import "Person.h"
@interface Person()
@property (nonatomic,strong,readwrite) NSArray *friends;
@end

@implementation Person
- (instancetype)initWithFristName:(NSString *)firstName withLastName:(NSString *)lastName{
    self = [super init];
    if (self) {
        _firstName = firstName;
        _lastName = lastName;
    }
    return self;
}
@end
  • 若想使类遵循的协议不为人知道,则可以在Class-continuation分类中声明
#import <Foundation/Foundation.h>
@class User;
@interface APP : NSObject
@property (nonatomic,strong) User *user;
@end

-----------------------------
#import "APP.h"
#import "User.h"
@interface APP()<UserDelegate>

@end
@implementation APP
-(void)doSomething{
    NSLog(@"dosomething");
}
@end
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容