views:

30

answers:

1

Is there any way define a object in a method, call a method of another object, and in that method use the first object:

-(IBAction)method{
    class * instance = [[class alloc] initWithValue:value];
    [instance method];
}

The method defined in class.m file:

-(void) method {
    instance.value = someOtherValue;
}
+1  A: 

The simple solution is to pass it in as a parameter:

[instance method:self];
...
- (void) method:(class *)caller { ...

To avoid coupling the two classes together too tightly, however, it is common to use a protocol to define the semantics of the callback, and to separate the method-call from the specification of the callback handler by assigning a delegate first, then calling methods. It's a bit involved, and I hope I have correctly covered all the details.

// Foo.h
@class Foo;

@protocol FooDelegate
- (void)doSomethingWithFoo:(Foo*)caller;
@end

@interface Foo {
    id<FooDelegate> delegate;
}

@property (nonatomic, retain) id<FooDelegate> delegate;

- (void)method;

@end

// Foo.m
@implementation Foo

@synthesize delegate;

- (void)method {
    [delegate doSomethingWithFoo:self];
}

@end

 

// Bar.h
#import "Foo.h"

@interface Bar<FooDelegate> {
}

// Bar.m
@implementation Bar

- (IBAction)method {
    Foo *foo = [[Foo alloc] init...];
    foo.delegate = self;
    [foo method];
}

- (void)doSomethingWithFoo:(Foo*)caller {
    NSLog(@"Callback from %@", caller);
}

@end
Marcelo Cantos