Duck
Duck

Reputation: 35953

cocoa - referencing a method on the parent

I had a method on my main view controller named "calculateThis".

This method was run, obviously, as

int newValue = [self calculateThis:myVariable];

when I run it from inside the view controller.

Then I created a static class and I need to run this method from there.

How do I reference this method from that class using just relative references, as super, superview, delegate, etc. I cannot use the class name defined on the delegate because this static class is used in several apps of mine.

I need to go up in the hierarchy, I imagine one level, and access the method there...

thanks.

Upvotes: 0

Views: 203

Answers (3)

falconcreek
falconcreek

Reputation: 4170

Define your utility methods in a category on NSObject or related subclasses of NSObject. Which you have done.

Adding (id)sender to your method will work. Then your method can reference the object that called it. Something like this.

+(int)calculateThis:(id)sender userInfo:(id)info;

then your call becomes.

int newValue = [NSObject calculateThis:self userInfo:myVariable];

Upvotes: 1

Shaggy Frog
Shaggy Frog

Reputation: 27601

Are you talking about the superclass? If so, you use [super ...].

Upvotes: 0

Jeff Kelley
Jeff Kelley

Reputation: 19071

If your intent is to create a class that you can use without initializing it, that's possible using class methods. For instance, if I want to make a class called MyClass with a doSomethingWith: method, I would define the following:

In MyClass.h:

@interface MyClass : NSObject {

}

+(void)doSomethingWith:(id)thisObject;

@end

In MyClass.m:

#import "MyClass.h"

@implementation MyClass

+(void)doSomethingWith:(id)thisObject
{
    // Your code goes here.
}

@end

To reference this method in another class, you can use the class object for MyClass like so:

[MyClass doSomethingWith:@"Hello, World!"];

This isn't really a typical Cocoa or Cocoa Touch design pattern, but can be handy for things like calculations.

Upvotes: 0

Related Questions