Subclassification of NSArray & NSMutableArray

Links for NSArray and NSMutableArray mention the possibility of subclassing, but this is only possible by providing your own repository and implementing methods

  • count

  • objectAtIndex:

for NSArrayas well

  • insertObject:atIndex:

  • removeObjectAtIndex:

  • addObject:

  • removeLastObject

  • replaceObjectAtIndex:withObject:

for NSMutableArray. This can be misleading, as it makes the programmer think that this is not possible using the simple means of subclassing NSArrayand NSMutableArray.

Thought it was impossible to create “simple” subclasses from them that use the existing support store (even if you do not access them directly), this is still possible with a small “workaround”.

, - , : 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" .

, ... !

Tomen =)

+3
1

NSMutableArray NSMutableArray - . - NS (Mutable) Array, , . , NSMutableArray C, , , . (Google CHCircularBuffer, ).   . , , .

+2

Source: https://habr.com/ru/post/1793113/


All Articles