NSArray和NSMutableArray的引用提到了创建子类的可能性,但这只能通过提供您自己的后备存储和方法的实现来实现
count
objectAtIndex:
对于NSArray
, 以及
insertObject:atIndex:
removeObjectAtIndex:
addObject:
removeLastObject
replaceObjectAtIndex:withObject:
为NSMutableArray
. 这可能会产生误导,因为它会导致程序员认为不可能通过简单的方法对 和 进行子类NSArray
化NSMutableArray
。
认为不可能创建它们的“简单”子类来利用现有的后备存储(即使您不直接访问它们),仍然可以通过一点“解决方法”。
因此,当我在寻找仍然能够对它们进行子类化的可能性时,我有一个简单的想法:只需创建子类并使用NSArray
or的实例NSMutableArray
作为后备存储。
下面是它的工作原理:
CSSMutableArray.h
#import <Foundation/Foundation.h>
@interface CSSMutableArray : NSMutableArray {
NSMutableArray *_backingStore;
}
@end
CSSMutableArray.m
#import "CSSMutableArray.h"
@implementation CSSMutableArray
- (id) init
{
self = [super init];
if (self != nil) {
_backingStore = [NSMutableArray new];
}
return self;
}
- (void) dealloc
{
[_backingStore release];
_backingStore = nil;
[super dealloc];
}
#pragma mark NSArray
-(NSUInteger)count
{
return [_backingStore count];
}
-(id)objectAtIndex:(NSUInteger)index
{
return [_backingStore objectAtIndex:index];
}
#pragma mark NSMutableArray
-(void)insertObject:(id)anObject atIndex:(NSUInteger)index
{
[_backingStore insertObject:anObject atIndex:index];
}
-(void)removeObjectAtIndex:(NSUInteger)index
{
[_backingStore removeObjectAtIndex:index];
}
-(void)addObject:(id)anObject
{
[_backingStore addObject:anObject];
}
-(void)removeLastObject
{
[_backingStore removeLastObject];
}
-(void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject
{
[_backingStore replaceObjectAtIndex:index withObject:anObject];
}
@end
如果你想子类NSArray
化,你只提供标题为的部分NSArray
。您现在可以从“自定义NSArray
子类的实现”中进行子类化并按照您的意愿工作。
希望这有帮助......和平!
托门 =)