English 中文(简体)
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!

最佳回答

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.

问题回答

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.

If you have a class with many properties it s very unlikely to initialize them all in one single line of code. Both ways work fine for me.

If an initWithSomething: method is available and you want to provide initial values for those properties, I would always prefer it just because it s simpler. It also will always work even with immutable versions of a class.

But neither init method is inherently "better." Classes usually have one or two designated initializers and all the others just call those with default values — it doesn t necessarily leave the instance s properties untouched. The documentation for a class should indicate what its initializers do and which is the designated initializer for the class. For example, [[NSDate alloc] init] uses NSDate s designated initializer, initWithTimeIntervalSinceReferenceDate:, to create a date object representing the current date and time.

Incidentally, this also means that when you re subclassing a class, you only need to override its designated initializer. Since the others just call that, they get your new behavior for free.





相关问题
Asynchronous request to the server from background thread

I ve got the problem when I tried to do asynchronous requests to server from background thread. I ve never got results of those requests. Simple example which shows the problem: @protocol ...

objective-c: Calling a void function from another controller

i have a void, like -(void) doSomething in a specific controller. i can call it in this controller via [self doSomething], but i don t know how to call this void from another .m file. I want to call ...

ABPersonViewController Usage for displaying contact

Created a View based Project and added a contact to the AddressBook using ABAddressBookRef,ABRecordRef now i wanted to display the added contact ABPersonViewController is the method but how to use in ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

NSUndoManager and runModalForWindow:

I have a simple Core Data app which displays a list of entities in the main window. To create or add new entities, I use a second modal window with a separate managed object context so changes can be ...

NSMutableArray values becoming "invalid"

I m trying to show a database information in a tableview and then the detailed information in a view my problem is as follow: I created a NSMutableArray: NSMutableArray *myArray = [[NSMutableArray ...

iPhone numberpad with decimal point

I am writing an iPhone application which requires the user to enter several values that may contain a decimal point (currency values, percentages etc.). The number of decimal places in the values ...

热门标签