Reputation: 1684
I'm still trying to wrap my head around how to best create and init custom classes in several ViewControllers.
Let's say I create a MyData class.
In FirstViewController, I wish to initialize it.
From one of the iPhone classes at college, a teacher suggested to use the following so that several instances of the same object are not created.
@property and @synthesize myData is done
-(MyData *)myData {
if (!myData) {
myData = [[MyData alloc] init];
}
return myData;
}
myData is released
Three things with this. If I put a MyData alloc init in one of the FirstViewController's methods, then I'm told every time that method is called, a new object is created which is consuming memory and is a potential for memory leaks. By creating the above getter, every time the object is used, the getter is called which seems like a waste of CPU cycles. If I don't do an alloc init, then the object is not created at all.
Lastly in subsequent views, I find I can get by just doing @property and @synthesize MyData in SecondViewController and then pass the myData object in the FirstViewController to it.
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
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