-1

I started learning programming about 8 months ago, started with C, OOP, now onto iOS, which is my goal. Everything is going pretty smooth for the most part and I've started to practice by programming small applications on xcode. It's just little terms like subroutine and convenience initializer that sometimes throw me off. Can anyone define these terms for me and just give me a quick example of their usage? In my demos I haven't had to use them but the lectures I study mention them, however they do not explain them very well. Not much info on these terms online either. Btw, I know these terms are totally unrelated

Any help is appreciated, thanks

2 Answers2

2

A convenience initializer is one that takes parameters so you can initialize your object with values other than nil.

1

A "subroutine" in Objective-C is called a method, and it consists of a specifier, a return value, and arguments. A class method can only be sent to the declaring class, and instance methods require an instance to be called.

A sample class method might look like this:

+(void)doMagicWithString:(NSString*)magicString;

And is called simply with:

[MyDeclaringClass doMagicWithString:@"Example"];

The + denotes it's class method status, doMagicWithString: is the actual name of the method, and magicString is its argument.

A sample instance method might look like this

-(CFRabbit*)beVewyQuiet:(BOOL)quiet imHuntingWabbits:(CFHunter*)hunter;

Which looks like this in C:

CFRabbit* beVewyQuiet(bool quiet, CFHunter* hunter);

This method returns an object of type CFRabbit* and can only be called by active instances of the class like so:

[self.myInstanceOfDeclaringClass beVewyQuiet:YES imHuntingWabbits:nil];

A "convenience initializer" (convenience method) is simply a message that replaces +alloc and -init with one quick and simple class method. For instance, NSArray's +array method returns an empty array, or NSDictionary's +dictionary method returns an empty dictionary.

Whereas before, it would take a message like this:

myArray = [NSArray alloc] init]; //long and unnecessary
CodaFi
  • 43,043
  • 8
  • 107
  • 153
  • 2
    Nit-pickery: A method is just one kind of subroutine. Functions and blocks are also subroutines. – Chuck May 19 '12 at 05:47