Objective-C 实例状态问题

silentwins 2018-12-17 12:49:20
抄了Cocoa的一个实例:


#import <Cocoa/Cocoa.h>

@interface ViewController : NSViewController
{
NSSpeechSynthesizer* _speechSynth;
}
- (IBAction)stopIt:(id)sender;
- (IBAction)sayIt:(id)sender;
@property (weak) IBOutlet NSTextField *textField;

@end




#import "ViewController.h"

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];

// Do any additional setup after loading the view.
}


- (void)setRepresentedObject:(id)representedObject {
[super setRepresentedObject:representedObject];

// Update the view, if already loaded.
}

- (id)init {
self = [super init];
if (self) {
// Logs can help the beginner understand what
// is happening and hunt down bugs.
NSLog(@"init");

// Create a new instance of NSSpeechSynthesizer
// with the default voice.
_speechSynth = [[NSSpeechSynthesizer alloc] initWithVoice:@"com.apple.speech.synthesis.voice.Alex"];
}
return self;
}

- (IBAction)stopIt:(id)sender {
NSLog(@"stopping");
[_speechSynth stopSpeaking];
}

- (IBAction)sayIt:(id)sender {
NSString *string = [_textField stringValue];
// Is the string zero-length?
if ([string length] == 0) {
NSLog(@"string from %@ is of zero-length", _textField);
return; }
// _speechSynth = [[NSSpeechSynthesizer alloc] initWithVoice:nil];
// [_speechSynth setVoice:@"com.apple.speech.synthesis.voice.Alex"];
[_speechSynth startSpeakingString:string];
while([NSSpeechSynthesizer isAnyApplicationSpeaking] == true) {}
NSLog(@"Have started to say: %@", string);
}
@end


如果代码如现在所描述,代码到[_speechSynth startSpeakingString:string];这一行是发不出声音出来的,而且我调试到_speechSynth此时是nil;

如果把
// _speechSynth = [[NSSpeechSynthesizer alloc] initWithVoice:nil];
// [_speechSynth setVoice:@"com.apple.speech.synthesis.voice.Alex"];
[_speechSynth startSpeakingString:string];
前两行的注释取消掉,程序就能正常发出声音,此时_speechSynth也不为nil。

请教一下为什么会这样,_speechSynth为什么没有持久化?谢谢!
...全文
253 1 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
wuzesong 2018-12-18
  • 打赏
  • 举报
回复
在初始化方法里面,你通过 _speechSynth = [[NSSpeechSynthesizer alloc] initWithVoice:@"com.apple.speech.synthesis.voice.Alex"]; 初始化了_speechSynth, 在 [_speechSynth startSpeakingString:string]; 的前面,你又通过 _speechSynth = [[NSSpeechSynthesizer alloc] initWithVoice:nil]; [_speechSynth setVoice:@"com.apple.speech.synthesis.voice.Alex"]; 这两行代码又对_speechSynth进行了赋值,如果你说注释掉这两行代码,就可以正常播放声音, 那么我觉得 [[NSSpeechSynthesizer alloc] initWithVoice:nil] 这个方法返回的就是个nil, 你可以点进 initWithVoice 这个构造方法里面去看下,看看里面是不是判断了后面的参数,如果参数为nil,也返回空对象(nil),才出现你说的这个问题,跟持久化没有关系。

29,049

社区成员

发帖
与我相关
我的任务
社区描述
主要讨论与iOS相关的软件和技术
社区管理员
  • iOS
  • 大熊猫侯佩
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧