Class-continuation分类
- Class-continuation分类和普通的分类不同,它必须定义在其所接续的那个类的实现文件中
- 此分类可以声明属性,且此分类没有特定的是现实文件,其中方法都定义在主实现文件中
- 一般存放不需要对外公开的属性(例子中的age)
代码语言:javascript
复制#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)
代码语言:javascript
复制#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分类中声明
代码语言:javascript
复制#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