0

Here's my setup. I subclassed UIViewController once to create a single "Widget" view controller that handles everything that all of my widgets can do. I then subclassed the Widget View Controller for each of my widgets, since they each handle their own unique and often complex set of functions.

I want to create an array of Widgets that stores each active widget in my scene, however I'm having trouble trying to figure out how to initialize the proper widget to store in the array. Initially I figured I could just do [widgets addObject:[[Widget alloc] initWithNibName:widgetName bundle:nil]];, however that completely ignores the individual widget initWithNibName function and goes right to the abstracted Widget class (which makes sense, since that's the class that I'm loading it into...).

How can I get my classes loaded into this array properly with each widget being initialized by its own unique subclass? Feel free to recommend structural changes as well, if necessary.

Rui Peres
  • 25,741
  • 9
  • 87
  • 137
Alec Sanger
  • 4,442
  • 1
  • 33
  • 53

3 Answers3

2

If the name of the class is the same as the nib

NSArray* widgets = [NSArray arrayWithObjects: @"MyVC1",@"MyVC2",nil];

NSString* newVC = [widgets objectAtIndex: value];

Class classVC = NSClassFromString(newVC);

Widget* controller = [[classVC alloc] initWithNibName:newVC bundle:nil];
Nico
  • 3,826
  • 1
  • 21
  • 31
0

Well instead of this:

[widgets addObject:[[Widget alloc] initWithNibName:widgetName bundle:nil]];

You can do this:

MySpecifc *mySpecificWidget = [[MySpecifc alloc] initWithNibName:widgetName bundle:nil];
[widgets addObject:myWidget];

My question here is, where is this NSMutableArray stored?

Myabe have a Singleton so you can keep track of them?

Community
  • 1
  • 1
Rui Peres
  • 25,741
  • 9
  • 87
  • 137
  • My NSMutableArray is stored at the scene-level, since the scene that is currently loaded handles all of the widgets. The problem is that I don't know what class MySpecific is at the time that it's called, so I can't declare it in my alloc without doing some sort of lookup. – Alec Sanger May 14 '12 at 13:35
0

I had a similar problem and I resolved the problem using a function like this in the "abstract" Widget class:

+ (Widget)InstanceFor(widgetType)type {
    switch(type) {
        case widgetTypeWidgetOne:
            return [[WidgetOne alloc] initWithNibName:@"WidgetOneName" bundle:nil] autorelease];
            break;
        case widgetTypeWidgetTwo:
            return [[WidgetTwo alloc] initWithNibName:@"WidgetTwoName" bundle:nil] autorelease];
            break;
    }
}

Where widgetType is this:

typedef enum {
    widgetTypeOne,
    widgetTypeTwo
} widgetType;

So you can store Widget object in the array and cast it when you need it. When you want to initialize a widget you can do that:

[widgets addObject:[Widget InstanceFor:widgetTypeWidgetOne]];
Marco Pace
  • 3,820
  • 19
  • 38