2010-10-24 67 views
0

使用的方法变量是否有任何方式的方法中定义一个对象,调用另一个对象的方法,以及在该方法中使用的第一对象:在目标C

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

在类中定义的方法。米的文件:

-(void) method { 
    instance.value = someOtherValue; 
} 
+0

你是什么意思?什么是“价值”和“someOtherValue”? – kennytm 2010-10-24 07:58:42

+0

值将是变量的原始值,其他值将是将分配给实例的新值。你的意思是什么具体的价值观? – bubster 2010-10-24 08:38:21

回答

1

的简单的解决方案是在将它作为一个参数:

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

为了避免耦合两个类然而,通常使用协议来定义回调的语义,并通过首先分配委托,然后调用方法来将方法调用与回调处理程序的规范分开。这有点牵扯,我希望我已经正确地覆盖了所有的细节。

// 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