obj-c编程15[Cocoa实例01]:一个会发声的随机数生成器

时间:2022-10-13 23:41:16

哇!终于到了obj-c编程系列的第15篇喽,一路走过来满不容易的哦!(怎么个意思,这才哪到哪啊!obj-c编程15[Cocoa实例01]:一个会发声的随机数生成器),为了能够更好的练习obj-c在Cocoa框架上的编程,接下来会以N篇Cocoa实例的博文来巩固和记忆前面和新学到的东西啊!

这15“章”的第1篇,我用一个简单的mac os x程序来开头吧,使用Xcode6beta(以后均称为x6b)编写,主要为Random类,其方法seed与按钮"reset random seed"绑定,方法generate与按钮"show rand number"绑定;其实例变量text_field与NSTextFieldCell控件绑定。为了增加趣味性,每当按下按钮会随机挑选系统中存在的一种语句报随机数,不多说了,下面上代码:

comm.h

//
//  comm.h
//  mac_test
//
//  Created by kinds on 14-7-4.
//  Copyright (c) 2014年 kinds. All rights reserved.
//

#import <Foundation/Foundation.h>

#define msg(...) NSLog(__VA_ARGS__)

Random.h

//
//  Random.h
//  mac_test
//
//  Created by kinds on 14-7-4.
//  Copyright (c) 2014年 kinds. All rights reserved.
//

#import "comm.h"
#import <Cocoa/Cocoa.h>

@interface Random : NSObject{
	IBOutlet NSTextField *text_field;
}

-(IBAction)seed:(id)sender;
-(IBAction)generate:(id)sender;

@end

Random.m

//
//  Random.m
//  mac_test
//
//  Created by kinds on 14-7-4.
//  Copyright (c) 2014年 kinds. All rights reserved.
//

#import "Random.h"

@implementation Random{
	NSSpeechSynthesizer *speech;
	NSArray *voices;
}

-(id)init{
	self = [super init];
	if(self){
		speech = [[NSSpeechSynthesizer alloc] initWithVoice:nil];
		voices = [NSSpeechSynthesizer availableVoices];
		msg(@"%@",voices);
	}
	return self;
}

-(void)set_voice{
	int idx = (int)(random() % [voices count]);
	[speech setVoice:[voices objectAtIndex:(NSUInteger)idx]];
}

-(IBAction)generate:(id)sender{
	int i = (int)(random() % 100000000000) + 1;
	msg(@"i = %d",i);
	[text_field setIntValue:i];
	[self set_voice];
	[speech startSpeakingString:[NSString stringWithFormat:@"%i",i]];
}

-(IBAction)seed:(id)sender{
	srandom((unsigned)time(NULL));
	NSString *str = @"the seed is reseted!";
	[text_field setStringValue:str];
	[speech startSpeakingString:str];
}

-(void)awakeFromNib{
	NSDate *now = [NSDate date];
	[text_field setObjectValue:now];
}

@end

窗口布局如下:

obj-c编程15[Cocoa实例01]:一个会发声的随机数生成器

程序执行界面如下,我恨不得做一个带声音的视频(看来本猫想多了):

obj-c编程15[Cocoa实例01]:一个会发声的随机数生成器