HM1
HM1

Reputation: 1684

How to initialize custom classes in ViewControllers?

I'm still trying to wrap my head around how to best create and init custom classes in several ViewControllers.

So why do I need alloc init to create the object in FirstVC and not in the SecondVC? Shouldn't I need to do that to allocate some memory for the object to be created so I can send in the reference?

Is there a better way of alloc init the object myData in the FirstVC that doesn't create multiple instances yet doesn't unnecessarily waste CPU cycles? (For those thinking CPU is cheap, what if you had many objects declared and think mobile)

Hope this makes sense. Thanks in advance,

Hiren.

Upvotes: 0

Views: 321

Answers (1)

Caleb
Caleb

Reputation: 124997

I'm not sure I can fully resolve your confusion, but here are a few ideas to consider:

First, don't worry about the load on the CPU associated with using property accessors. If that's where your bottleneck is, either you're doing very well or your app isn't doing very much. It's great to be conscious of potential performance issues; it's not so great to fix them before you know that there's really a problem.

Second, why not just initialize your properties in your -initWithNibName:bundle: method? Like this:

-(id)initWithNibName:(NSString*)name bundle:(NSString*)bundle
{
    if (self = [super initWithNibName:name bundle:bundle]) {
        myData = [[MyData alloc] init];
    }
    return self;
}

The code you showed looks a bit like what one might use to create a singleton, i.e. a class that can only be instantiated once. Could that be what your teacher was talking about? It's not something you need to do most of the time.

I'm not sure how to address your issue with the second view controller... I think there's some more confusion there, and since we don't have any code to talk about, it's hard to proceed. If you're using the "modern" Objective-C runtime, you can declare properties without providing matching instance variables, and perhaps that's what you're doing, but you still need to initialize your properties before you use them.

Upvotes: 1

Related Questions