gpt4 book ai didi

objective-c - 以实例创建者作为接收者调用方法

转载 作者:行者123 更新时间:2023-12-03 17:11:53 25 4
gpt4 key购买 nike

我有 A 类(NSDocument 子类),它存储我的文档数据。 A 类创建 B 类(NSView 子类)的一个实例,用于管理 View 。我希望每次调用B类的drawRect:方法时,它都会调用A类的updateChangeCount:,以便用户知道要保存文档。

最佳答案

我并不完全熟悉 OSX 项目以及 drawRect:NSView 的具体作用,因此您可能需要查看 Richard J Ross III 的评论。但关于一个对象调用实例化它的对象上的方法的一般问题:

B类.h

@protocol ClassBDelegate <NSObject>
@reqiured
- (void)someRequiredMethod;
@optional
- (void)someOptionalMethod;
@end

@interface ClassB <NSView>
@property (nonatomic, assign) id<ClassBDelegate> delegate;
// Other stuff you need in your interface
@end

B类.m

- (void)someClassBMethodThatNeedsToTriggerSomeClassAMethod {
// stuff
[self.delegate someRequiredMethod];

if ([self.delegate respondsToSelector:@selector(someOptionalMethod)]) {
[self.delegate someOptionalMethod];
}
// stuff
}

现在,在 ClassA 中,请确保您遵守此协议(protocol):

#import ClassB.h

@interface ClassA <ClassBDelegate>

并实现所需的方法:

- (void)someRequiredMethod {
// stuff
NSLog(@"Hello world!");
// stuff
}

当您实例化 ClassB 对象时,请务必将其委托(delegate)设置为您自己:

classB.delegate = self;  
<小时/>

编辑:注意,我举了一个示例,说明 ClassB 如何使用可选方法以及必需方法。

关于objective-c - 以实例创建者作为接收者调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21646795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com