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 = newFreq开发者_Go百科uency;
}
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.
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:
- How do I pass multiple parameters in Objective-C?
- Is there a language out there in which parameters are placed inside method name?
精彩评论