Search code examples
objective-cif-statementbooleanself

If statement in Objective C


I'm sure this is super simple but I just started using Objective C and I'm trying to compare a response with the answer of the object to see if the response is right but I keep getting a compiler error. Im kind of confuse about the "self" and how to get the answer stored in the question object. Thanks.

- (BOOL) verifyAnswer:(Answer *)response
{
    if (response isEqual:[self.answer])
       return YES;
    else
       return NO;
}

Solution

  • You get an error because that's not valid Objective-C syntax. In Obj-C methods are called using the square bracket syntax like this:

    [object method];
    

    Or with arguments:

    [object methodWithArgument:arg1 otherArgument:arg2];
    

    In your case you're trying to call the method isEqual: of the NSObject class (the root class of most Cocoa classes). You call this method on any object and pass it as an argument an other object to compare. So the correct syntax is this:

    if ([response isEqual:self.answer])
    

    Please read The Objective-C Programming Language carefully.