Lyd
Lyd

Reputation: 2096

Initialize an array of another class type in Objective C

I have a variable usuario of type TuplaUsuario. When I insert its data, I want to initialize NSMutableArray cups to an Array of type TuplaCups. How can I do it?

Here is my code up to date:

TuplaUsuario:

//TuplaUsuario.h:
@interface TuplaUsuario : NSObject
{
    NSMutableString* mensaje;
    NSString* usuario;
    NSString* password;
    NSMutableArray* cups;
    //More variables
}
//Property for each variable
- (id)initWithString:(NSString *)identifier;

//TuplaUsuario.m:
//Synthesize for each variable
- (id)initWithString:(NSString *)identifier {
    if ( self = [super init] ) {
        mensaje = [[NSMutableString alloc] initWithString:identifier];
        usuario = [[NSString alloc] initWithString:identifier];
        password = [[NSString alloc] initWithString:identifier];
        cups = [[NSMutableArray alloc] init];
    }
    return self;
}

TuplaCups:

//TuplaCups.h:
@interface TuplaCups : NSObject {
    NSString* cups;
    NSString* tarifa;
    NSString* direccion;
    NSString* nombreUsuario;
    NSMutableArray* facturas;
}
//Property for each variable
- (id)initWithString:(NSString *)identifier;

//TuplaCups.m:
//Synthesize for each variable
- (id)initWithString:(NSString *)identifier {
    if ( self = [super init] ) {
        cups = [[NSMutableString alloc] initWithString:identifier];
        tarifa = [[NSString alloc] initWithString:identifier];
        direccion = [[NSString alloc] initWithString:identifier];
        nombreUsuario = [[NSString alloc] initWithString:identifier];
        facturas = [[NSMutableArray alloc] init];
    }
    return self;
}

Upvotes: 0

Views: 226

Answers (2)

Lance
Lance

Reputation: 9012

Objective-C doesn't have a concept of Generics like C# or C++ do. There are no templates after all. You just have to know what type of objects you've put into an array. If you are going to intermix them, you can use isKindOfClass: to test for the class.

Upvotes: 1

DarkDust
DarkDust

Reputation: 92335

Arrays (as in NSArray and NSMutableArray) in Objective-C are not typed, they can hold any object type and you can't easily restrict what's going in. So you are responsible for ensuring that only objects of the type you want go in. Usually, this isn't a problem unless you expose the mutable array so that other objects might put stuff into your array. In this case, it's better to provide accessors:

- (void)addFoo:(Foo *)foo {
    [myMutableArray addObject:foo];
}

- (void)removeFoo:(Foo *)foo {
    [myMutableArray removeObject:foo];
}

// Return an array of Foo instances.
- (NSArray *)foos {
    return [[myMutableArray copy] autorelease];
}

Upvotes: 1

Related Questions