gpt4 book ai didi

ios - 自定义委托(delegate)不更新 iOS 中的 UI

转载 作者:行者123 更新时间:2023-12-01 17:39:10 24 4
gpt4 key购买 nike

我编写了一个自定义委托(delegate)来监听麦克风音频数据的变化及其长度。当委托(delegate)方法中的数据发生变化时,主 Controller 绘制音频波。结果是主 Controller 中的麦克风数据和长度确实发生了变化,但绘图不显示。

.h 中的委托(delegate)声明:

@class SXDetectAlgorithm;

@protocol SXDetectAlgorithmDelegate <NSObject>

- (void)detectAlgorihtm:(SXDetectAlgorithm *)detectAlgorihtm outputBufferValue:(float *)micBuffer withBufferSize:(UInt32)bufferSize;

@end

@interface SXDetectAlgorithm : NSObject <EZMicrophoneDelegate>

@property (nonatomic, weak) id<SXDetectAlgorithmDelegate> delegate;

@end

在 .m 中实现委托(delegate):
// Use third party API to get microphone data
-(void) microphone:(EZMicrophone *)microphone
hasAudioReceived:(float **)buffer
withBufferSize:(UInt32)bufferSize
withNumberOfChannels:(UInt32)numberOfChannels {

// Process the microphone data and then feed to "micBuffer"
...
...
...

// Back to the main thread to respond delegate
dispatch_async(dispatch_get_main_queue(), ^{

SXMainController *mainController = [[SXMainController alloc] init];
self.delegate = mainController;
[self.delegate detectAlgorihtm:self outputBufferValue:micBuffer withBufferSize:bufferSize];
});

在 mainController.h 中声明委托(delegate):
@interface SXMainController () <SXDetectAlgorithmDelegate> 

@property (nonatomic, strong) SXDetectAlgorithm *detectAlgorithm;

@end

使用 Delegate 在 mainController.m 中绘制波形:
-(id)initWithCoder:(NSCoder *)aDecoder{

if(self = [super initWithCoder:aDecoder]) {
self.detectAlgorithm = [[SXDetectAlgorithm alloc] init];
}
return self;
}

- (void)detectAlgorihtm:(SXDetectAlgorithm *)detectAlgorihtm
outputBufferValue:(float *)lpfout
withBufferSize:(UInt32)bufferSize {

dispatch_async(dispatch_get_main_queue(), ^{

// Plot method...
// Use a button to test if it can display
UIButton *testButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
testButton.backgroundColor = [UIColor redColor];
[self.view addSubview:testButton];
});
}

我的问题是,即使我返回主线程来绘制波形或显示按钮,mianController 的 UI 也根本不会更新。想了半天问题出在哪里。有人可以给我建议吗?

谢谢。

最佳答案

SXMainController *mainController = [[SXMainController alloc] init];
self.delegate = mainController;
[self.delegate detectAlgorihtm:self outputBufferValue:micBuffer withBufferSize:bufferSize];

每次您收到音频数据时,此代码都会创建一个新的 viewController,这很可能不是您想要实现的。

您可能想要做的是在创建检测对象后将您的 viewController 设置为委托(delegate),因此:
-(id)initWithCoder:(NSCoder *)aDecoder{

if(self = [super initWithCoder:aDecoder]) {
self.detectAlgorithm = [[SXDetectAlgorithm alloc] init];
self.detectAlgorithm = self;
}
return self;
}

然后打电话
self.delegate detectAlgorihtm:self outputBufferValue:micBuffer withBufferSize:bufferSize];

从另一个对象

关于ios - 自定义委托(delegate)不更新 iOS 中的 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27504923/

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