XCode: Checking and assigning split string values to textField
So i have been trying to test this out; basically i have a text file included named rawData.txt, it looks like this:
060315512 Name Lastname
开发者_如何学Python050273616 Name LastName
i wanted to split the lines and then split each individual line and check the first part (with 9 digits) but it seems to not work at all (my window closes) is there any problem with this code?
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++;
}
}
Yes if you want to compare 2 string you should use isEqualToString, because == compares the pointer value of the variables. So this is wrong:
if ([[line objectAtIndex:0] stringValue] == @"060315512")
You should write:
if ([[[line objectAtIndex:0] stringValue] isEqualToString: @"060315512"])
If you check your console log, you probably see something like "stringValue sent to object (NSString) that does respond" (or those effects). line
is an array of strings, so [[line objectAtIndex:0] stringValue]
is trying to call -[NSString stringValue]
which does not exist.
You mean something more like this:
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];
}
}
}
精彩评论