如下所述,一个超类,名字是ZpIOObject
typedef NS_OPTIONS(NSUInteger, ZpIOObjectType) {
ZpIOObjectType_NONE = 0 , // is no exist file or no judgment object type
ZpIOObjectType_File , // it's a file object
ZpIOObjectType_Document // it's a document object
};
@interface ZpIOObject:NSObject
@property (nonatomic , assign ) ZpIOObjectType fileType ;
@property (nonatomic , strong ) NSString *absolutePathString ;
/**create an object or subobject*/
+(instancetype) ioObjectWithAbsolutePathString:(NSString *)absolutePathString ;
@end
一个子类,名称为ZpIOFileObject
@interface ZpIOFileObject : ZpIOObject
- (void)fileDataWithAsynchronize:(void(^)(NSData *fileData))result ;
@end
另一个子类,名称是ZpIODocumentObject
@interface ZpIODocumentObject : ZpIOObject
@property (nonatomic , strong , readonly) NSArray<ZpIOObject*> *subIOObjects ;
@end
@implementation ZpIODocumentObject
@synthesize subIOObjects = _subIOObjects ;
- (NSArray<ZpIOObject *>*)subIOObjects
{
if( nil == self.absolutePathString || YES == [[self.absolutePathString trim] isEqualToString:emptyString] ){
return nil ;
}
if( nil != self.error ){
return nil ;
}
// 进行IO操作,获取最新的文件当前层级的子文件、子文件夹,一定是最新数据,但对IO开销大
NSFileManager *fileManager = [NSFileManager defaultManager] ;
NSError *error ;
NSArray<NSString*>* subDirsNameArr = [fileManager contentsOfDirectoryAtPath:self.absolutePathString error:&error] ;
if( nil == subDirsNameArr || 0 == [subDirsNameArr count] ){
return nil ;
}
for( NSString *subFilePathString in subDirsNameArr ){
NSMutableString *subFileAbsolutePathString = [[NSMutableString alloc] initWithString:subFilePathString] ;
[subFileAbsolutePathString appendString:[NSString stringWithFormat:@"/%@",subFilePathString]] ;
ZpIOObject * ioobject = [ZpIOObject ioObjectWithAbsolutePathString:subFileAbsolutePathString] ;
switch ( ioobject.fileType ) {
case ZpIOObjectType_File:{
; // How to convert ZpIOObject to ZpIOFileObject ??????
}
case ZpIOObjectType_Document:{
; // How to convert ZpIOObject to ZpIODocumentObject ??????
}
break;
default:{/*do nothing*/}break ;
}
}
return nil ;
}
@end
你可以看到这个代码:
switch ( ioobject.fileType ) {
case ZpIOObjectType_File:{
; // How to convert ZpIOObject to ZpIOFileObject ??????
}
case ZpIOObjectType_Document:{
; // How to convert ZpIOObject to ZpIODocumentObject ??????
}
break;
default:{/*do nothing*/}break ;
}
我想将 ZpIOObject 转换为 ZpIOFileObject/ZpIODocumentObject 。
我想你会认为很容易:创建 ZpIOFileObject/ZpIODocumentObject 和赋值。例如:
ZpIOFileObject *fileObject = [[ZpIOFileObject alloc] init] ;
fileObject.property = ioobject.property
... do something ...
不!我不想要这个.
我想要一个超类转换为子类,为什么?在我看来,ioObject是一个现有的对象,创建(分配)一个新对象(例如[[ZpIOFileObject alloc]init])是浪费内存资源!
我不忍心浪费内存资源!
所以,我的问题是:
如果超类是现有对象,如何将超类的对象转换为子类的对象?
测试了很长时间,我敢肯定,做不到。
子类的对象可以转换为超类的对象,但超类的对象不能转换为子类的对象。
for example :
A inheritance ASuper
A *a = [[A alloc] init] ;
ASuper * aSuper = a ; // right
A *aAnother = (A *) aSuper ; // right
ASuper * aSuperAnother = [[ASpuer alloc]init] ;
A *a_other = aSuperAnother ; // Error !