XCode:检查并将拆分字符串值分配给textField

时间:2011-10-02 22:03:25

标签: xcode split textfield assign

所以我一直试图测试这个;基本上我有一个名为rawData.txt的文本文件,它看起来像这样:

    060315512 Name Lastname
    050273616 Name LastName

我想分割线然后拆分每一行并检查第一部分(9位数)但它似乎根本不起作用(我的窗口关闭)这段代码有问题吗?

    NSString *path = [[NSBundle mainBundle] pathForResource: @"rawData" ofType:@"txt"];
    if (path)
    {
        NSString *textFile = [NSString stringWithContentsOfFile:path]; 
        NSArray *lines = [textFile componentsSeparatedByString:(@"\n")];
        NSArray *line;
        int i = 0;
        while (i < [lines count])
        {
            line = [[lines objectAtIndex:i] componentsSeparatedByString:(@" ")];
            if ([[line objectAtIndex:0] stringValue] == @"060315512")
            {
                idText.text = [[line objectAtIndex: 0] stringValue];    
            }
            i++;
        }
    }

2 个答案:

答案 0 :(得分:0)

是,如果你想比较2个字符串你应该使用isEqualToString,因为==比较变量的指针值。所以这是错误的:

if([[line objectAtIndex:0] stringValue] == @“060315512”)

你应该写:

if([[line objectAtIndex:0] stringValue] isEqualToString:@“060315512”])

答案 1 :(得分:0)

如果你检查你的控制台日志,你可能会看到类似“stringValue发送到对象(NSString)确实响应”(或那些效果)。 line是一个字符串数组,因此[[line objectAtIndex:0] stringValue]正在尝试调用不存在的-[NSString stringValue]

你的意思是更像这样:

NSString *path = [[NSBundle mainBundle] pathForResource: @"rawData" ofType:@"txt"];
if (path)
{
    NSString *textFile = [NSString stringWithContentsOfFile:path]; 
    NSArray *lines = [textFile componentsSeparatedByString:@"\n"];
    for (NSString *line in lines)
    {
        NSArray *columns = [line componentsSeparatedByString:@" "];
        if ([[columns objectAtIndex:0] isEqualToString:@"060315512"])
        {
            idText.text = [columns objectAtIndex:0];
        }
    }
}