3

NSArrayNSMutableArrayのリファレンスには、サブクラスを作成する可能性が記載されていますが、これは、独自のバッキングストアとメソッドの実装を提供することによってのみ可能です。

  • count

  • objectAtIndex:

のためNSArrayに、そして

  • insertObject:atIndex:

  • removeObjectAtIndex:

  • addObject:

  • removeLastObject

  • replaceObjectAtIndex:withObject:

のためにNSMutableArrayNSArrayこれは、プログラマーがサブクラス化とを単純な手段では不可能であると考えるようになるという点で誤解を招く可能性があり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、必要に応じて作業できます。

これがお役に立てば幸いです...平和!

トーメン=)

4

1 に答える 1

2

でサブクラスNSMutableArray化してバックアップすることNSMutableArrayは、無意味で恐ろしい考えです。NS(Mutable)Arrayのような基本的なものをサブクラス化する場合は、少なくともそうする理由があります。たとえば、私はサブクラスを持っていて、それを循環バッファーNSMutableArrayとして機能させるために C 配列でサポートしているので、前部での挿入と削除は後部と同じくらい高速です。(興味のある方は Googleで検索してください。) ただし、ほとんどの場合、サブクラス化にはほとんど、またはまったく意味がありません。また、自明なサブクラスを作成するのは簡単かもしれませんが、有用で意味のあるサブクラスを作成するのは自明ではありません。CHCircularBuffer

于 2011-02-20T05:47:52.830 に答える