I'm trying to create global function in Objective-C. I created new .m and h. file with subclass of viewcontroller.
This is Connection.m
#import "Connection.h"
@interface ViewController () <NSStreamDelegate>
@property (strong,nonatomic) NSInputStream * inputStream;
@property (strong,nonatomic) NSOutputStream * outputStream;
@end
@implementation ViewController(Connection)
-(void)initNetworkCommunication {
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"192.168.0.10", 35000, &readStream, &writeStream);
self.inputStream = objc_unretainedObject(readStream);
self.outputStream = objc_unretainedObject(writeStream);
[self.inputStream setDelegate:self];
[self.outputStream setDelegate:self];
[self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self.outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self.inputStream open];
[self.outputStream open];
}
Connection.h
#import "ViewController.h"
@interface ViewController(Connection)
-(void)initNetworkCommunication;
@end
ViewController.m
#import "ViewController.h"
#import "Connection.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)ConnectionButton:(id)sender {
[self initNetworkCommunication];
}
@end
I tryed 3 methods mentioned in How to create global functions in Objective-C but no one of this 3 works. First two(create a class method in a static class and declare a global function instead of class) don't work because when I change "-(void)... to +(void).. every "self..." gets error and same in second method. Only third one works for me (adding a category to NSObject for your methods) but when I'm trying to call [self initNetworkCommunication] function program crashesh with signal SIGABRT and I can't solve that problem. Any ideas how I can call this function?
UPDATE: @gronzzz
Connection.m
@interface ViewController () <NSStreamDelegate>
@property (strong,nonatomic) NSInputStream * inputStream;
@property (strong,nonatomic) NSOutputStream * outputStream;
@end
@implementation Connection
-(void)initNetworkCommunication
Connection.h
#import "ViewController.h"
@interface Connection : ViewController
-(void)initNetworkCommunication;
@end
ViewController.h
#import "ViewController.h"
#import "Connection.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)callMethod
{
Connection *detailVC = [[Connection alloc] init];
[detailVC initNetworkCommunication];
}
- (IBAction)ConnectionButton:(id)sender {
[self callMethod];
}
@end
And Signal SIGABRT show when [self callMethod] is called.