Very strange problem. I've been testing my little command line program which reads a file and parses through it and it is working fine with my test data but when I went after the real thing it couldn't find the file.
The original file was a text file put together by text edit and the actual file was saved from Microsoft Word in MS-Dos format. When I tried to read the MS Word file, it couldn't find it. I did not get an error but did get a nil string back from the file loading method. I then renamed my test file to the same name and it got the original test data. Huh? At worst, I figured I'd see some sort of odd looking data loaded into my string... not nil.
Here is a stylized portion of code snippet. Please ignore the 'catch and release' code around the Datafile NSString... I realize I don't need to do it in that way and that is not the point of the question.
datafilename is set to 'config1.txt'.
(NSString*) OpenEntryFile: (NSString*) pathname withdatafilename: (NSString*) datafilename {
NSStringEncoding encoding;
NSError* error = nil;
NSString* inputdatafile;
NSString* response;
NSString *homeDir = NSHomeDirectory();
NSString *fullPath开发者_C百科 = [homeDir stringByAppendingPathComponent:datafilename];
filepointer = 0;
[Datafile release];
inputdatafile = [NSString stringWithContentsOfFile: fullPath usedEncoding:&encoding error:&error];
Datafile = [inputdatafile copy];
response = [NSMutableString stringWithString: @"OK"];
if (error) {response = [NSMutableString stringWithString: @"ERROR"];};
if ([Datafile length] < 60) {response = [NSMutableString stringWithString: @"SHORT"];};
return response;
}
This code has a number of issues;
Datafile
should bedataFile
the
if(error)
is wrong; only by checking the return value can you know if an error was generated.there is no need to use
NSMutableString
for your responses. Just use the constant string directly.there is no need to copy the data as read with
stringWithContentsOfFile:
; just retain the resulting string (if you get one).if you are getting
nil
forinputdatafile
, then an error would have been generated. I.e. the returned string cannot be nil withouterror
containing a description of the problem.
i.e. this will always output either a string or an error:
if (inputdatafile)
NSLog(@"%@", inputdatafile);
else
NSLog(@"error %@", error);
From a comment:
if ([error code]) {response = [NSMutableString stringWithString: @"ERROR"];}
This is completely wrong.
The rules are that you must check the return value prior to checking the error. Always and without exception.
To do otherwise will yield crashes and other erroneous behavior.
精彩评论