Reputation: 1
I have a simple question about syntax:
NSString* inpword1 = @"eight";
NSString* outword1 = [lookFor theKey:inpword1]; // This line does not compile!!!!
-(NSString*) lookFor: theKey: (NSString*) key; // in the Spec (translator.h)
-(NSString*) lookFor: theKey: (NSString*) key; // in the Body (translator.m)
{
NSString* entry = [[NSString alloc] init];
entry = [dictionary objectForKey:key];
return entry;
}
Everything compiles except for the one line. If there is an obvious problem with the syntax, I haven't been able to figure it out. Any help would be appreciated. I am able to look up words in the dictionary correctly but when I use the lookFor as a wrapper, I can't seem to get the syntax right for the call.
Upvotes: 0
Views: 1180
Reputation: 5035
Edit:
Before pointing out the Syntax errors, i have to make it clear that you shouldn't create you own function to retrieve an object for key. this has already been done for you, simply call [someDictionary objectForKey:@"YourKey"];
now to our syntax problems- I see 3 main problems here:
NSString* entry = [[NSString alloc] init]; //this allocation is useless and will result in a memory leak because later, you assign it with an object from the dictionary:
[lookFor theKey:inpword1]; //This is just a wrong way to call a function:
-(NSString*) lookFor: theKey: (NSString*) key //this is just a wrong way to declare a function.
you probably meant:
NSString* inpword1 = @"eight";
NSString* outword1 = [self lookForKeyInDict:dict TheKey:inpword1];
-(NSString*) lookForKeyInDict:(NSDictionary*)dict TheKey:(NSString*) key;
-(NSString*) lookForKeyInDict:(NSDictionary*)dict TheKey:(NSString*) key
{
NSString* entry;
entry = [dict objectForKey:key];
return entry;
}
Upvotes: 2
Reputation: 7220
The syntax [lookFor theKey:inpword1];
means you're calling the method theKey:
with inpword1
as an argument on an object named lookFor
.
The syntax -(NSString*) lookFor: theKey: (NSString*) key;
declares a method lookFor:theKey:
which takes an NSString*
called key
as an argument and returns an NSString*
. Unfortunately the use of the colon after lookFor
means that when you try to call this method, theKey
will be treated as an argument and you'll get an undeclared error. You should never use a colon in a method name unless it's introducing a parameter, as with theKey:
.
So, in a nutshell, I'd just keep in mind:
[
in Objective-C is the name of the object you're calling.Upvotes: 2
Reputation: 112873
In the statement:
NSString* outword1 = [lookFor theKey:inpword1]; // This line does not compile!!!!
lookFor
is an instance of some object.
theKey
is the message being sent to the object.
The class lookFor
must have a method thekey
with a type of NSString *
Additionally there seems to be confusion on Objective-C message structure, consider reading the Apple documentation on Objective-C, it will save you a lot of time.
Upvotes: 2