在 Objective c 的方法中使用变量

发布于 2024-09-29 13:10:10 字数 287 浏览 4 评论 0原文

有没有办法在方法中定义一个对象,调用另一个对象的方法,并在该方法中使用第一个对象:

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

class.m 文件中定义的方法:

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

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;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你的笑 2024-10-06 13:10:11

简单的解决方案是将其作为参数传递:

[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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文