0

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;
}
2
  • What do you mean? What are value and someOtherValue? Commented Oct 24, 2010 at 7:58
  • value would be the original value to the variable and someothervalue would be a new value that would be assigned to instance. Do you mean what are the specific values? Commented Oct 24, 2010 at 8:38

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.