0

I wonder is there any drawbacks when use alloc/free with pure C array inside Objective-C class? For example:

#import "CVPatternGrid.h"

@implementation CVPatternGrid

@synthesize row = _row;
@synthesize column = _column;
@synthesize count = _count;
@synthesize score = _score;

- (id)initWithRow:(NSInteger)row column:(NSInteger)column {
    if (self = [super init]) {
        _grid = [self allocateNewGrid:row column:column];
    }
    return self;
}

- (NSInteger)moveCount {
    return _count;
}

- (bool**)allocateNewGrid:(NSInteger)row column:(NSInteger)column {
    bool **p = malloc(row * sizeof(bool*));
    for (int i = 0; i < row; ++i) {
         p[i] = malloc(column * sizeof(bool));
    }
    return p;
}

- (void)generateNewGrid:(NSInteger)row column:(NSInteger)column {
    [self freeGrid];
    _grid = [self allocateNewGrid:row column:column];
    _count = [self.algorithmDelegate generateGrid:_grid];
    _score = _count * 100;
}

- (BOOL)isMarkedAtRow:(NSInteger)row column:(NSInteger)column {
    return YES;
}

- (void)freeGrid {
    for (int i = 0; i < _row; ++i) {
        free(_grid[i]);
    }
    free(_grid);
}

- (void)dealloc {
    [self freeGrid];
}

@end
roxrook
  • 13,511
  • 40
  • 107
  • 156
  • It's not done very often, but there are cases where it's appropriate. Be aware that C arrays and properties don't work and play well together -- it can be done but requires a minor tap dance. – Hot Licks Apr 18 '14 at 02:47

1 Answers1

0

It's perfectly normal to use a C array in an Obj-C class. There are no low level data types in Obj-C — every class, including NSArray, NSString, etc, is using primitive C types internally.

However you are doing a few things wrong:

Do not use @synthesize unless you need to. In this case you don't need it, so delete those lines of code.

Do not use _foo to access variables unless you need it, again in this case you don't need it in any of your use cases (except, arguably, in your init and dealloc methods. But I would argue it should not even be used there. Other people disagree with me). My rule is to only use _foo when I run into performance issues when using self.foo syntax. There are also edge case issues such as KVO where you might run into problems when using an accessor inside init/dealloc. In the real world I have never run into any of those edge cases in more than 10 years of writing Obj-C — I always use accessors, unless they're too slow.

Some implementation details about how to declare an @property of a C array: Objective-C. Property for C array

Community
  • 1
  • 1
Abhi Beckert
  • 32,787
  • 12
  • 83
  • 110