自定义格式化程序奇怪的行为

时间:2012-03-31 15:38:14

标签: objective-c cocoa textfield nsformatter

我有一个自定义 NSFormatter 链接到4个 NSTextFields 。当我手动更改文本字段的值时,一切正常。但是当我通过组合框更改它时。我得到一个如下错误:

-[__NSCFNumber length]: unrecognized selector sent to instance 0xc0c3

我注意到应用程序不断发送此错误,并且实例始终相同( 0xc0c3 )。此外,当我的 NSTextFields 未链接到我的自定义格式化程序时,即使通过组合框也能正常运行。

你们知道问题的根源可能是什么?

提前致谢!

以下是一些代码:

组合框动作: - (void)subnetMaskByNumberOfSubnetBits:(id)sender {

// ------- Sets the subnet mask when the user selects the number of bits

NSNumberFormatter *stringToNumber = [[NSNumberFormatter alloc] init];//TURN A STRING INTO A NUMBER
NSNumber *selectedAmountOfBits = [[NSNumber alloc] init];//CONTAINS THE SELECTED NUMBER OF BITS

selectedAmountOfBits = [stringToNumber numberFromString:[sender objectValueOfSelectedItem]];

[self changeSubnetMaskUsingNumberOfMaskBits:selectedAmountOfBits];

//RELEASE
[stringToNumber release];

}

- (void)changeSubnetMaskUsingNumberOfMaskBits:(NSNumber *)numberOfMaskBitsSelected {

// --------- Change the subnet mask based on the number of bits


NSInteger numberOfFullOctets;
NSInteger valueOfLastOctet;
NSInteger octetCounter;
NSMutableDictionary *subnetMaskFields = [[NSMutableDictionary alloc] init];



//Contains keys to all the outlets
[subnetMaskFields setObject:subnetMaskOctet1 forKey:@"subnetMaskField1"];
[subnetMaskFields setObject:subnetMaskOctet2 forKey:@"subnetMaskField2"];
[subnetMaskFields setObject:subnetMaskOctet3 forKey:@"subnetMaskField3"];
[subnetMaskFields setObject:subnetMaskOctet4 forKey:@"subnetMaskField4"];


//NUMBER OF FULL OCTETS AND VALUE OF LAST OCTET
numberOfFullOctets = [numberOfMaskBitsSelected intValue]/8;

valueOfLastOctet = 256 - pow(2, 8 - ([numberOfMaskBitsSelected intValue] - (8 * ([numberOfMaskBitsSelected intValue]/8)))); //Big complicated formula


//-------Setting the fields------//

//SETTING THE FIELDS OF FULL OCTETS
for (octetCounter = 1; octetCounter <= numberOfFullOctets; octetCounter++) { 
    [[subnetMaskFields objectForKey:[NSString stringWithFormat:@"subnetMaskField%i", octetCounter]] setStringValue:@"255"];
}

//SETTING THE FIELD OF THE INCOMPLETE OCTET
[[subnetMaskFields objectForKey:[NSString stringWithFormat:@"subnetMaskField%i", octetCounter]] setIntegerValue:valueOfLastOctet];


//FILLING THE ZER0S
while (octetCounter < 4) {

    octetCounter++;
    [[subnetMaskFields objectForKey:[NSString stringWithFormat:@"subnetMaskField%i", octetCounter]] setStringValue:@"0"];


}

//RELEASE
[subnetMaskFields release];

}

1 个答案:

答案 0 :(得分:0)

问题在于这行代码:

[[subnetMaskFields objectForKey:[NSString stringWithFormat:@"subnetMaskField%i", octetCounter]] setIntegerValue:valueOfLastOctet];

据我所知,由于NSFormatter需要获取我的文本字段的string value,因此我无法将文本字段设置为整数。这行代码

[[subnetMaskFields objectForKey:[NSString stringWithFormat:@"subnetMaskField%i", octetCounter]] setStringValue:[NSString stringWithFormat:@"%ld", valueOfLastOctet]]; 

解决了这个问题。