0

I've been trying to do an ios app with:

  • a viewcontrolloer with some functions/methods

  • a new class with a pointer to these functions/methods so that class1.point2f () would work

    // testclass header
    @property void (*point2f)();
    
    
    // viewcontroller header        
    #import "testclass.h"
    
    @interface ViewController : UIViewController
    {
        testclass *test;
    }
    
    @property testclass *test;
    
    @end
    
    
    // viewcontroller implementation
    void downx() 
    {
        NSLog(@"hello");
    };
    
    - (void)viewDidLoad
    {
        [super viewDidLoad];
    
        test.point2f = downx;
    
        test.point2f ();     // crashes only at this line
    

I would be very thankfull for answers or at least keywords I could look into further.

anothermh
  • 9,815
  • 3
  • 33
  • 52

1 Answers1

0

The problem is that you are trying to call a NULL function pointer. In objective-c, instance variables are initialized to nil (NULL). So the variable test is nil. It is not an error to access a property of a nil pointer but that does not do anything. Therefore, test.point2f = downx; does nothing and test is still nil. Every property of a nil pointer also returns nil (0, NO etc..). So test.point2f is actually nil. So effectively what you're doing is

((void (*)())NULL) ();    // dereferencing a NULL pointer

You need to instantiate a testclass object and assign it to test before accessing any of it's properties.

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.test = [[testclass alloc] init];
    test.point2f = downx;
    test.point2f();     // won't crash anymore

    // rest of your code
}
Ahmed Mohammed
  • 1,134
  • 8
  • 10