Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C - preferred way to create and initialize an object

Is one of these two ways to create and initialize an object preferable?

MyClass oClass = [[MyClass alloc] init];
oClass.length = 5;
oClass.text = @"Hello";

or using a class method that contains about the same code but looks like this:

MyClass oClass = [MyClass myClassWithLength:(int) 5 andText:(NSString *) @"Hello"];

I hate it when I see things done more than one way and I have no idea if one is better than the other, or why!

like image 686
Scott Pendleton Avatar asked Mar 10 '10 15:03

Scott Pendleton


2 Answers

Don't be a hater. :-)

By the way, I'm assuming you meant:

(Edit: removed unnecessary casts)

MyClass oClass = [[MyClass alloc] initWithLength:5 andText:@"Hello"];

The reason for multiple init... methods is to make it more convenient for developers to create properly initialized instances. So, for example, if you find that developers often need to create instances of MyClass with a length and text, you make their life easier by providing an API that allows them to do that in one step. And if you find that developers also frequently need to create instances of MyClass with just a text string, you might also provide an -initWithText: method.

And if the instances created this way are frequently used as temporary objects (i.e., not stored in instance variables or static variables), you might also add a class convenience method like +myClassWithText: that returns an autoreleased instance of MyClass initialized with the provided text string.

As to which one is better: it's always better to fully initialize an object when possible, so if the object needs both values to be properly initialized, use the method that allows you to provide both arguments. And if you don't need to store a reference to the instance you're creating, use the class convenience method so your code doesn't have to deal with memory management.

like image 195
jlehr Avatar answered Nov 17 '22 20:11

jlehr


If the object is unusable without the length and text, then the second option might be better. If those fields are optional, then the first one is better.

However, I don't think there is absolute truth to this question.

like image 34
Tuomas Pelkonen Avatar answered Nov 17 '22 22:11

Tuomas Pelkonen