Search code examples
objective-cxcodeclasspointerscontrollers

Creating reference to another class, Objective C


In my first file I want to be able to get reference to my second file and change a property that it has, This is what I have. I made a class method to return the reference but the problem is I get a warning in the method, on top of that when I do the if statement it doesnt seem to run.

First File that needs reference, calls class method to get reference

-(void) updateSplitViewDetail{

id detail =  (MapViewController*) [MapViewController returnReference];
NSLog(@"%@", [detail class]); //This post MAPVIEWCONTROLLER

//This fails so I cant access the methods inside.
if ([detail isKindOfClass:[MapViewController class]]) {
    MapViewController *mapVC = (MapViewController*) detail;
    mapVC.delegate = self;
    mapVC.annotations = [self mapAnnotations];
}

}

 (void)viewDidLoad
  {
[super viewDidLoad];    
[self updateSplitViewDetail]; //Error may be here?
  }

Second File that I want reference to, returns reference using self.

- (void)viewDidLoad
{

NSLog(@"%@", [self class]);

[super viewDidLoad];
self.mapView.delegate = self;
// Do any additional setup after loading the view.
}

+(MapViewController*) returnReference{
//I also get an incompatible pointer return warning here?
return self;
}

Solution

  • +(MapViewController*) returnReference {
        //I also get an incompatible pointer return warning here?
        return self;
    }
    

    You get a warning because this is a class method (see the +) therefore this is of type Class not of type (MapViewController*). It refers to the MapViewController class not to an instance of that class. And the pointer you are returning is the class itself, not an instance. This is why the test fails and you cannot call the instance methods in the other code.

    You probably want to instantiate the class and return the instance instead.