Search code examples
objective-cgenericscollectionsstrong-typing

Creating an array that contains only objects of a given class


Ok, so I have the code below (Objective-C FYI) and I was wondering if I want to create an NSMutableArray of c_data objects, how would I go about doing that? It's sort of like declaring a List<c_data> cData in C#.

@interface c_data : NSObject {
    double value;
    int label;
    int ID;
}    
@property double value;
@property int label;
@property int ID;

-(c_data*) init;
-(c_data*) initWithValue:(double)value;    
@end

@implementation c_data
@synthesize value, label, ID;
-(c_data*) init {
    return self;
}
-(c_data*) initWithValue:(double)val {
    value = val;
    return self;
}
@end

If you look at the class feat_data, I'm trying to make cData an array of the class c_data. I have included my attempts at it, but I don't think it's right because c_data isn't an array. Any suggestions?

@interface feat_data : NSObject {
    NSMutableArray *nData;
    NSMutableArray *cData;
    char type;
}
@property(nonatomic, retain) NSMutableArray *nData;
@property(nonatomic, retain) NSMutableArray *cData;
@property char type;
-(feat_data*)init;
@end

@implementation feat_data
@synthesize nData, cData, type;
-(feat_data*)init {
    nData = [[NSMutableArray alloc] init];
    c_data *c_dataInstance = [[c_data alloc] init];
    cData = [[NSMutableArray alloc] initWithArray:c_dataInstance];
    return self;
}
@end

Solution

  • [NSMutableArray addObject:[[[c_data alloc] init] autorelease]];
    

    Objective-C arrays aren't typed. It seems you have some C++ unlearning to do.

    On a related note, your inits are pretty bad. You need to call super init as well, as such:

    - (id)init {
      self = [super init];
      if (self != nil) {
        //Initialize here.
      }
      return self;
    }