NSString的问题:使用控制器设置NSTextField?

时间:2012-10-17 18:27:28

标签: objective-c nsstring nstextfield

我正在使用Xcode 4编写一个简单的程序来根据用户输入生成文本。我成功地从两个文本字段读取,但我无法将结果发送到单独的NSTextField。我相信我已经在IB中建立了所有正确的连接,并且我正在向NSTextField发送setStringValue方法。我创建了一个ScaleGenerator对象,我认为该对象可能不正确地创建了字符串本身。我的Controller标题如下所示:

#import <Cocoa/Cocoa.h>

@interface Controller : NSObject
{
    IBOutlet NSTextField * notesField;
    IBOutlet NSTextField * midiField;
    IBOutlet NSTextField * resultField;
    IBOutlet id scalegenerator;
}    
- (IBAction) generate: (id) sender;
@end // Controller

Controller实现如下:

#import "Controller.h"
#import "ScaleGenerator.h"
#import <Foundation/foundation.h>

@implementation Controller

- (IBAction) generate: (id) sender
{
    int midinote;
    int notes;
    NSString * scale;

    midinote = [midiField intValue];
    if(midinote < 0 || midinote > 127) {
        NSRunAlertPanel(@"Bad MIDI", @"That MIDI note is out of range! (0 - 127)", @"OK", nil, nil);
        return;
    }

    notes = [notesField intValue];
    if(notes < 2 || notes > 24) {
        NSRunAlertPanel(@"Bad Scale Size", @"You must have at least two notes in your scale, and no more than 25 notes!", @"OK", nil, nil);
        return;
    }

    scale = [scalegenerator generateScale: midinote and: notes];

    [resultField setStringValue:scale];   
}  
@end

我的ScaleGenerator代码如下所示:

#import "ScaleGenerator.h"
#import <math.h>

@implementation ScaleGenerator

- (NSMutableString *) generateScale: (int) midinote and: (int) numberOfNotes
{
    double frequency, ratio;
    double c0, c5;
    double intervals[24];
    int i;
    NSMutableString * result;

    /* calculate standard semitone ratio in order to map the midinotes */
    ratio = pow(2.0, 1/12.0);       // Frequency Mulitplier for one half-step
    c5 = 220.0 * pow(ratio, 3);     // Middle C is three semitones above A220
    c0 = c5 * pow(0.5, 5);          // Lowest MIDI note is 5 octaves below middle C
    frequency = c0 * pow(ratio, midinote); // the first frequency is based off of my midinote

    /* calculate ratio from notes and fill the frequency array */
    ratio = pow(2.0, 1/numberOfNotes);
    for(i = 0; i < numberOfNotes; i++) {
        intervals[i] = frequency;
        frequency *= ratio;
    }

    for(i = 0; i < n; i++){
        [result appendFormat: @"#%d: %f", numberOfNotes + 1, intervals[i]];
    }

    return (result);
}
@end // ScaleGenerator

我的ScaleGenerator对象有一个功能,我相信我可能会搞砸了。什么样的字符串可以迭代地将格式化文本附加到??我叫什么方法?

1 个答案:

答案 0 :(得分:1)

您尚未分配/初始化NSMutableString。因此,消息appendFormat:转到nil。替换

NSMutableString * result;

NSMutableString * result = [[NSMutableString alloc] init];