I have a method (the code below is a simplified version) that parses small text files:
- (void)parseFile:(NSString *)aFile
{
NSDate *date;
NSNumber *number;
NSString *desc;
NSString *txt = [NSString stringWithContentsOfFile:aFile encoding:NSUTF8StringEncoding error:nil];
for (NSString *line in [txt componentsSeparatedByString:@"\n"]) {
if ([linesubstring isEqual:@"mydate"]) {
date = [dateFormat dateFromString:strDate];
}
if ([linesubstring isEqual:@"mynu开发者_运维知识库mber"]) {
number = [numberFormat numberFromString:strValue];
}
if ([linesubstring isEqual:@"mydesc"]) {
desc = [line substringWithRange:NSMakeRange(0, 10)];
}
if (!date && !number && !desc) {
...do something...
}
}
}
The first problem is that date
variable is being filled with the content of aFile
parameter. It only assumes it's correct value, when the passes through the fist if/check.
So why? I though that date
could be a reserved word and exchanged it, but with the same behavior.
The second problem is with the last if (with the nested ones). Debuging the code, i can see that xcode shows it as "out of scope", but !number
fails (xcode thinks that it's valid)...
I tried other combinations, like [number isNotEqualTo:[NSNull null]]
(this one throws an error EXC_BAD_ACCESS), without success.
Please, could anybody give some hints? I'm newbie with cocoa/objective-c. I'm coming from java...
TIA,
Bob
There's quite a few things wrong with the code you've provided. I'm using the answer box because there isn't enough room for this to be a comment:
With regards to your variable declarations:
NSDate *date;
NSNumber *number;
NSString *desc;
You have correctly declared them, but you have not initialised them. As they are, they could be pointing to any random garbage. This means that your test at the end of the loop…
if (!date && !number && !desc) {
...do something...
}
…may in fact always execute because date
, number
and desc
may always be non-zero (I say may because it is actually undefined whether they are zero or non-zero). Initialise each of them to nil
if you plan to determine whether they are set or not:
NSDate *date = nil;
NSNumber *number = nil;
NSString *desc = nil;
It is not always necessary to initialise variables (for example, as long as you write to it before you read from it, it is not necessary to initialise it), however some people promote the idea of initialising all variables to prevent this undefined behaviour from surfacing (I typically initialise all variables even if I overwrite the initialised value anyway).
Also, there is a variable called linesubstring
but it is not declared anywhere in the code, similarly strDate
, strValue
are not declared anywhere either. It is important to know how these are declared and how these are used as they may similarly be pointing to garbage.
精彩评论