UITextField和有趣的程序

时间:2012-01-02 15:25:44

标签: iphone xcode

首先,对不起我的英语......我想编写一个计算两个城市之间距离的程序。例如,在UITextField我们写巴黎,在第二个UITextField我们写第二个,“伦敦。我们有所有城市的经度和纬度的基础。我们的程序有使用这四个数字的距离公式。我们知道这个公式。

当用户在UITextField中插入名称时,我想获取此文本并将其与我们的基础进行比较。怎么做??我可以做一个这样的程序,但它是......愚蠢的:

@interface City : UIViewController{

    IBOutlet UITextField *city1;

    IBOutlet UITextField *city2;
}

@property (nonatomic, retain) IBOutlet UITextField *city1;
@property (nonatomic, retain) IBOutlet UITextField *city2;

-(void) calculate;

@end




#import "City.h"

@implementation City

@synthesize city1, city2;

-(void) viewDidLoad
{
    // to check changes in textfields i`m using NSTimer, I know it`s stupid but I haven`t learned how to make it in different way

    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(calculate) userInfo:nil repeats:YES];

}

-(void) obliczenia
{
    double distance;


    if([city1 is EqualToString:@"Paris"] && [city2 is EqualToString:@"London"])
    {

        double Paris_lat = x1;
        double Paris_lon = y1;
        double London_lat = x2;
        double London_lon = y2;

        distance =...; // we know the formula for distance but this is not important for now.
              // distance shows in some label but this is not a point of my problem. 

    }
}

它运行但我们的城市很少。但是,当我们有数千个城市时,编写代码将是一个不可见的。

我开始使用iPhone编程。 谢谢您的耐心等待,请帮助我。这很重要,但我找不到解决方案。

3 个答案:

答案 0 :(得分:4)

看一下本指南: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/PropertyLists/AboutPropertyLists/AboutPropertyLists.html

基本上,将所有数据放入属性列表中,如下所示:

<dict>
    <key>Paris</key>
    <dict>
        <key>x</key>
        <real>20.2</real>
        <key>y</key>
        <real>30.4</real>
    </dict>
...
</dict>

然后像这样加载它:

NSDictionary * data = [[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"NAMEOFPLIST" ofType:@"plist"]];
NSDictionary * paris = [data objectForKey:@"Paris"];
float xparis = [[paris objectForKey:@"x"] floatValue];
float yparis = [[paris objectForKey:@"y"] floatValue];

在你的情况下,你会做这样的事情:

NSDictionary * data = [[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"NAMEOFPLIST" ofType:@"plist"]];
NSDictionary * city1Data = [data objectForKey:city1.text];
NSDictionary * city2Data = [data objectForKey:city2.text];
if (city1Data != nil && city2Data != nil) {
     // Do what you need...
}

然后用数据做你需要的。

答案 1 :(得分:1)

您最好使用选择器视图显示可用的城市,或使用文本视图中的实时搜索进行自动填充,或为您的城市提供选择。

如果您有一组受约束的输入(在这种情况下,您拥有long,lat值的城市的名称),最好将用户的输入限制为这些值。

答案 2 :(得分:0)

您可以创建一个包含所有国家/地区名称的数组,并将数组中的每个国家/地区名称与您的输入进行比较。

  NSArray *countries = [NSArray arrayWithObjects:@"Berlin", @"Rom", nil];

  for (NSString *c in countries) {
    if ([city1 isEqualToString:c]) {
      //do something
    }
  }
相关问题