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

Class-continuation分类

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

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

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

#import 
@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 
@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 
@class User;
@interface APP : NSObject
@property (nonatomic,strong) User *user;
@end

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

@end
@implementation APP
-(void)doSomething{
    NSLog(@"dosomething");
}
@end

你可能感兴趣的:(协议与分类--27:Class-continuation分类隐藏实现细节)