user1078265
user1078265

Reputation: 21

Calling a class method from another class in Objective-C (Cocoa)

I'm new to programming in Cocoa, so I'm still struggling to grasp some basic concepts.

What I want to do (as an example) is write an application with multiple NSTextFields. However, these NSTextFields need to be linked to separate classes. Additionally, each separate class needs to be able to get and set data from each other.

I tried to add methods to tackle this problem, to no avail. Let's say this is a method in the textbox's original class, and I want to call it from another class.

-(void)settextfield:(NSString*)stringy;
{
    [TextField setStringValue:stringy];
}   

Here's the calling code (we're calling this from another class, TestClass)...

-(IBAction)test:sender;
{
 [BundleBrowseTextBox settextfield: @"Testy"];
}

Nothing happens. There's probably some obvious way to do this, but I haven't been able to unearth this via Google searches.

Upvotes: 0

Views: 255

Answers (4)

user1078265
user1078265

Reputation: 21

My mistake was that I was calling the class method instead of the instance... you can call the instance via IBOutlets and defining those outlets properly in Interface Builder.

Upvotes: 1

Ray Garner
Ray Garner

Reputation: 932

I believe you forgot your parameter type in your original post this...

      -(IBAction)test:sender;
      {
        [BundleBrowseTextBox settextfield: @"Testy"];
      }

should be

   -(IBAction)test:(id)sender;
   {
      [BundleBrowseTextBox settextfield: @"Testy"];
   }

That aside if you understand the difference between class and instance as you say you do. Then it would be nice if you would show us the rest of your implementation and interface. The problem is probably not in the code snippets you showed us.

Upvotes: 0

voidref
voidref

Reputation: 1123

You need to make sure the pointers you are using are not nil.

One odd/convenient thing about objC is that you can pass messages to nil and it won't crash.

Upvotes: 0

Mike Fahy
Mike Fahy

Reputation: 5707

If I'm right in assuming you're trying to set the text in an instance of BundleBrowseTextBox, you should call the settextfield: message on the instance name, rather than on the class name (if BundleBrowseTextBox IS the instance -- rather than the class -- you should really avoid capitalized instance names for clarity). i.e.:

-(IBAction)test:(id)sender;
{
   // Assuming bbtBox is defined as an instance of BundleBrowseTextBox
   [bbtBox settextfield: @"Testy"];
}

Upvotes: 0

Related Questions