Gestione Matrici in Object-C

MacOSX, Object-C Soft! Commenta l'articolo

Se avete bisogno di lavorare con Matrici in Object-C vi fornisco due classi di esempio per imparare:

intMatrix

@interface intMatrix : NSObject {
    int *matrix;
    int rows;
    int columns;
}

@property(readonly) int rows;
@property(readonly) int columns;

-(intMatrix *) initWithRowsCount:(int)i columnsCount:(int)j initValuesToZero:(BOOL)choice;
-(int) intValueAtRow:(int)i column:(int)j;
-(void) setIntValue:(int)value atRow:(int)i column:(int)j;

@end

#import "intMatrix.h"

@implementation intMatrix

@synthesize rows;
@synthesize columns;

// messaggi di init e dealloc
-(intMatrix *) initWithRowsCount:(int)i columnsCount:(int)j initValuesToZero:(BOOL)choice {
    if(self = [super init]) {
        matrix = malloc(sizeof(int) * i * j);
        rows = i;
        columns = j;
        
        if(choice == YES) {
            for(i = 0; i < rows; i++) {
                for(j = 0; j < columns; j++) {
                    matrix[i * columns + j] = 0;
                }
            }
        }
    }
    
    return self;
}
-(void) dealloc {
    free(matrix);
    [super dealloc];
}

// messaggi di get e set di un valore in posizione i, j
-(int) intValueAtRow:(int)i column:(int)j {
    return matrix[i * columns + j];
}
-(void) setIntValue:(int)value atRow:(int)i column:(int)j {
    matrix[i * columns + j] = value;
}

@end

E più in generale:


@interface ObjMatrix : NSObject {
    id *matrix;
    int rows;
    int columns;
}

@property(readonly) int rows;
@property(readonly) int columns;

-(ObjMatrix *) initWithRowsCount:(int)i columnsCount:(int)j;
-(id) objValueAtRow:(int)i column:(int)j;
-(void) setObjValue:(id)value atRow:(int)i column:(int)j;

@end

ObjMatrix

#import "ObjMatrix.h"

@implementation ObjMatrix

@synthesize rows;
@synthesize columns;

// messaggi di init e dealloc
-(ObjMatrix *) initWithRowsCount:(int)i columnsCount:(int)j  {
    if(self = [super init]) {
        matrix = malloc(sizeof(id) * i * j);
        rows = i;
        columns = j;
        
    }
    
    return self;
}
-(void) dealloc {
    free(matrix);
    [super dealloc];
}

// messaggi di get e set di un valore in posizione i, j
-(id) objValueAtRow:(int)i column:(int)j {
    return matrix[i * columns + j];
}
-(void) setObjValue:(id)value atRow:(int)i column:(int)j {
    matrix[i * columns + j] = value;
}

@end

Scrivi un Commento

Home | Graffiti e Disegni | Educazione | Chi siamo | Blog | Progetti | Contatti
RSS Feed Comments RSS Accedi