2009-12-08 78 views
0

试图制作一个iPhone应用程序,并通过我之前的人推荐的教程和书籍:)我试图找到有关scanf /将用户输入数据从文本字段存储到变量,我可以稍后在我的程序中使用。文本字段实际上是一个数字字段,所以我试图保存它们输入的整数,而不是文本,因为在我的情况下不会有任何内容。我在这里走错了路吗?任何帮助将不胜感激。使用Scanf与ObjC和iPhone

回答

1

样,如果我本质试图 保存输入的情况下数量 与

你想NSNumberFormatter开始的。数据格式化程序( Apple Guide)处理字符串转换以及格式化输出。

1

我认为,而不是scanf,你只是希望从文本字段获取值作为NSString指针。

如果在界面中使用UITextField,可以通过将变量声明为IBOutlet并将其连接到Interface Builder中,将UITextField连接到类中的成员变量。

然后,您可以使用[UITextField variable name] .text作为NSString指针访问文本值。

有许多有用的函数来处理NSString或将字符串转换为其他数据类型,如整数。

希望这会有所帮助!

+0

如果我基本上试图保存输入是一个数字开始呢? – HollerTrain 2009-12-08 18:20:28

+0

您可以使用NSString上的intValue方法在字符串和数字之间轻松转换。 – 2009-12-09 17:52:42

0

下面是如何从文本字段中获取整数的示例。

在您的.h文件中:

#include <UIKit/UIKit.h> 

@interface MyViewController : UIViewController { 
    UITextField *myTextField; 
} 

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

- (IBAction)buttonPressed1:(id)sender; 

@end 

在您.m文件:

#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 

在Interface Builder中,您的视图控制器的myTextField将出口连接到文本字段,你想价值来自。将buttonPressed1动作连接到按钮。

希望这会有所帮助!