0

I've tried searching google and this site regarding my question but found no answer.

I'm a beginner with Obj-C and would like this question answered.

What is the benefit of using parameters in my methods.

for example..

 -(id)initWithName:(NSString *)newName atFrequency:(double)newFreq { 
self = [super init]; 
if (self != nil) {
name = newName; 
frequency = newFrequency;
} 
return self;
}

versus

 -(void)myMethod {
self = [super init];
if (self != nil) {
name = newName;
frequency = newFrequency;
}
return self;
}

I understand that the -(void) means the method has no return type, and the -(id) means that the first method has 'id' as a return type, and 'id' is generic....

can anyone help explain? I hope my question makes sense, thank you all for your help.

Instafal
  • 11
  • 1
  • 2

1 Answers1

0

Parameters are inputs to a method, just like function/method parameters in any language. In your second example, on the line frequency = newFrequency;, where is newFrequency supposed to come from?

In other languages, where you might have something like

void initWithName(string newName, double newFreq);

In Obj-C the equivalent is

- (void)initWithName:(NSString *)newName atFrequency:(double)newFreq;

The difference is that in Obj-C, there is an extra piece of the method name for each parameter (like the atFrequency) — in this case, the method name is initWithName:atFrequency:, not just initWithName:.

(This is actually optional, you only have to have a : for each parameter. Technically initWithName:: is still a valid method name, but that's not considered good practice in Obj-C.)

See also:

Community
  • 1
  • 1
jtbandes
  • 115,675
  • 35
  • 233
  • 266
  • Hey, thanks for your reply jtbandes.. but what I'm trying to understand is , is there a benefit to using parameters? Couldn't I just write a method that does the same thing without the parameters in my method name? – Instafal Aug 25 '11 at 03:58
  • @Instafal How would you pass any input to such a method? – jtbandes Aug 25 '11 at 03:59
  • I think I just figured it out... when I use parameters in my method it only helps explain what my method does when I'm reading it.. whereas if I don't use parameters and my method returns void, I'd have to take an extra step and send my object the method. With parameters and when a function returns 'id' I can just save my self the step by doing "MyClass *object = [[MyClass alloc]initWith:parameter1:parameter2]; – Instafal Aug 25 '11 at 04:03