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.
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With