Pregunta

[Background] I'm trying to write a simple length converter in objective C. I've set up a button that upon clicking should take the value entered in a text field and run a conversion outputting the value to another text field. My original implementation had the conversion code written within the button's (IBAction) method which worked fine. Now I want to extend the functionality to include conversions from any selected length to any other. In order to do this I've written the conversion code in a subclass (I've also attempted a category) of NSObject where I will be able to change the conversion factors depending on the selections. I have attempted to follow the information provided by apple to no avail. I just can't see what I'm missing!!

[My code] I've set up my subclass interface as follows:

#import <Foundation/Foundation.h>

@interface ConversionCode : NSObject

@property (readonly) NSString *KmString;

- (NSString*) convertLength:(NSString *)LengthIn;

@end

And my implementation:

#import "ConversionCode.h"

@implementation ConversionCode

- (NSString*) convertLength:(NSString *)LengthIn
{
    float milesFVal = LengthIn.floatValue;
    float KmOutVal = milesFVal * 1.609;
    NSString *Km = [NSString stringWithFormat:@"%f",KmOutVal];
    _KmString = Km;
    return _KmString;
}

@end

I want the convertLength method to be invoked from my GUI controller class from within the button click method as such:

- (IBAction)ClckCvtBttn:(id)sender{

    ConversionCode *convert = [[ConversionCode alloc]init];
    NSString *Km = [convert convertLength];
    [_KmOut setStringValue:Km];

}

This is written exactly as the apple documentation suggests but it simply will not work! I've tired all sorts of additional ways to point to the conversion code object including an @property declaration in the controller class's interface and IBOutlet in the interface writing it as an overrride etc. Please can anyone tell me what I'm missing?

¿Fue útil?

Solución

The method in interface is - (NSString*) convertLength:(NSString *)LengthIn;

While you are using : NSString *Km = [convert convertLength];

You should use :

NSString *anyString = @"24";
NString *Km = [convert convertLength:anyString];

Your full IBAction method:

- (IBAction)ClckCvtBttn:(id)sender{

    ConversionCode *convert = [[ConversionCode alloc]init];
    NSString *anyString = @"24";
    NString *Km = [convert convertLength:anyString];
    [_KmOut setStringValue:Km];

}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top