NSArrayとNSMutableArrayのリファレンスには、サブクラスを作成する可能性が記載されていますが、これは、独自のバッキングストアとメソッドの実装を提供することによってのみ可能です。
count
objectAtIndex:
のためNSArray
に、そして
insertObject:atIndex:
removeObjectAtIndex:
addObject:
removeLastObject
replaceObjectAtIndex:withObject:
のためにNSMutableArray
。NSArray
これは、プログラマーがサブクラス化とを単純な手段では不可能であると考えるようになるという点で誤解を招く可能性がありNSMutableArray
ます。
既存のバッキングストアを利用する「単純な」サブクラスを作成することはできませんが(直接アクセスしない場合でも)、少しの「回避策」によって可能です。
そのため、サブクラス化できる可能性を探していたときに、サブクラスを作成して、NSArray
または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
、必要に応じて作業できます。
これがお役に立てば幸いです...平和!
トーメン=)