0

I know what a function is, but I am trying to write a few into my project. I have just watched a video series on Objective-C from Lynda.com where I got the idea from.

In the video is it is explained that I can write a function like this:

void declareWebView ()

However if I write it like that into my code, the error comes up and says that my _webView and self (as self.view) are not available.

if I write it like this:

-(void) declareWebView

Then I do not have an issue.

Any ideas on how to get the first one right? As far as I can tell, I cannot set any parameters with the second way of writing.

2 Answers 2

2

The first is as you said called a function. It is part of the C part of Objective-C, and is not connected to objects or classes, so the variable self or any instance variables of an object don't have any meaning. You can pass it variables that are objects though like so:

void my_func(NSString *string, id someObject, int someInt);

void my_func(NSString *string, id someObject, int someInt)
{
    NSLog(@"string = %@, someObject = %@, someInt = %d",string,someObject,someInt);
}

The second is a method, and in a method you can access self and, within instance methods, access instance variables. Replacing the "-" in front of the method with a "+" makes it a class method. In a class method you can't access instance variables and self refers to the class itself, not an instance.

Hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

0

The first way is written in the language C. The second way is written in Objective-C. Objective-C methods must be declared the second way. You cannot access your object's private members and properties from within a C function directly, but you could use accessor methods on the Objective-C object and call them from a C function.

1 Comment

Cool that sorts it, I will stick with the second one then :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.