开发者

Using Scanf with ObjC and iPhone

trying to make an iPhone app and going through the tutorials and books recommended by those before me :) I'm trying to find information on the scanf/s开发者_高级运维toring user input data from a text field into a variable which I can use later in my program. The text field is actually a number field, so I am trying to save the integers they input and not the text since there won't be any in my case. Am I on the wrong path here? Any help would be greatly appreciated.


what about if i am essentially trying to save the input that is a number to begin with

You want NSNumberFormatter. The data formatters ( Apple Guide) handle conversions to and from strings as well as formatting for output.


I think rather than scanf, you're just looking to get the value from the text field as an NSString pointer.

If you use a UITextField in your interface, you can connect the UITextField to a member variable in your class by declaring the variable as an IBOutlet and connecting it in Interface Builder.

You can then access the text value as an NSString pointer by using [UITextField variable name].text.

There are many useful functions to work with NSStrings or convert the string to other datatypes such as integers.

Hope this helps!


Here's an example of how to get an integer out of a text field.

In your .h file:

#include <UIKit/UIKit.h>

@interface MyViewController : UIViewController {
    UITextField *myTextField;
}

@property (nonatomic, retain) IBOutlet UITextField *myTextField;

- (IBAction)buttonPressed1:(id)sender;

@end

In your .m file:

#include "MyViewController.h"

@implementation MyViewController

@synthesize myTextField;

- (IBAction)buttonPressed1:(id)sender {
    NSString *textInMyTextField = myTextField.text;
    // textInMyTextField now contains the text in myTextField.

    NSInteger *numberInMyTextField = [textInMyTextField integerValue];
    // numberInMyTextField now contains an NSInteger based on the contents of myTextField

    // Do some stuff with numberInMyTextField...
}

- (void)dealloc {
    // Because we are retaining myTextField we need to make sure we release it when we're done with it.
    [myTextField release];
    [super dealloc];
}

@end

In interface builder, connect the myTextField outlet of your view controller to the text field you want to get the value from. Connect the buttonPressed1 action to the button.

Hope this helps!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜