Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a function from another class file

I am very familiar with writing VB based applications but am new to Xcode (and Objective C). I have gone through numerous tutorials on the web and understand the basics and how to interact with Interface Builder etc. However, I am really struggling with some basic concepts of the C language and would be grateful for any help you can offer. Heres my problem…

I have a simple iphone app which has a view controller (FirstViewController) and a subview (SecondViewController) with associated header and class files.

In the FirstViewController.m have a function defined

@implementation FirstViewController

- (void) writeToServer:(const uint8_t *) buf {
    [oStream write:buf maxLength:strlen((char*)buf)];   
}

It doesn't really matter what the function is.

I want to use this function in my SecondViewController, so in SecondViewController.m I import FirstViewController.h

#import "SecondViewController.h"
#import "FirstViewController.h"

@implementation SecondViewController

-(IBAction) SetButton: (id) sender {
    NSString *s = [@"Fill:" stringByAppendingString: FillLevelValue.text];
    NSString *strToSend = [s stringByAppendingString: @":"];
    const uint8_t *str = (uint8_t *) [strToSend cStringUsingEncoding:NSASCIIStringEncoding];
    FillLevelValue.text = strToSend;

    [FirstViewController writeToServer:str];
}

This last line is where my problem is. XCode tells me that FirstViewController may not respond to writeToServer. And when I try to run the application it crashes when this function is called.

I guess I don't fully understand how to share functions and more importantly, the relationship between classes.

In an ideal world I would create a global class to place my functions in and call them as required.

Any advice gratefully received.

like image 295
Guy Parker Avatar asked Apr 23 '10 07:04

Guy Parker


1 Answers

In the deklaration of your method:

- (void) writeToServer:(const uint8_t *) buf;

The - at the beginning of the declaration indicates, that it is an instant method. This means, you have to create an instance of your class to call it. If there were a +, the method would be a class method and you could call it the way you do in your code.

Example:

@interface MyClass
{ }
 - (void) myInstanceMethod;
 + (void) myClassMethod;
@end

Then in some function:

[MyClass myClassMethod]; // This is ok

//[MyClass myInstanceMethod]; // this doenst't work, you need an instance:

MyClass *theInstance = [[MyClass alloc] init];
[theInstance myInstanceMethod];
like image 143
gammelgul Avatar answered Oct 08 '22 07:10

gammelgul