Naming convention for Objective C initializers?
For Objective C clases like NSString
with multiple initializers the convention seems to be to provide a default initializer init
and then multiple initWith...
initializers:
– init
– initWithBytes:length:encoding:
– initWithBytesNoCopy:length:encoding:freeWhenDone:
– initWithCharacters:length:
...
However, suppose I have an Objective C class that has only one initializer and that initializer takes multiple arguments. Does convention dictate that I still call it:
- initWithSomeStuff:thing1:thing2:thing3:
Or can it s开发者_StackOverflowimply be called:
- init:thing1:thing2:thing3:
All objects respond to the init method, even if it is not over-ridden by a subclass. As for your example I would still include "with" for sake of readability. Read out loud what the method is doing and you'll notice including "with" makes what your doing more poignent.
As Avizzv92 wrote, every subclass of NSObject
has the -init
initialiser inherited from NSObject
, so technically your subclass of NSObject
would have two initialisers. A common practice is to have one designated initialiser and have other initialisers call it with default arguments.
As for your -init:thing1:thing2:thing3:
idea, it is certainly possible. However, consider the following method definition:
- (id)init:(id)param0 thing1:(id)param1 thing2:(id)param2 thing3:(id)param3 {
// …
}
It is easy to understand that param1
refers to thing1
, param2
refers to thing2
, and param3
refers to thing3
. But what is param0
? That’s the reason why initialisers with parameters have names that start with initWithSomething
: to make it clear what the first parameter is.
精彩评论