Re: stringWithUTF8String: Question
Re: stringWithUTF8String: Question
- Subject: Re: stringWithUTF8String: Question
- From: "Clark S. Cox III" <email@hidden>
- Date: Tue, 6 May 2003 08:49:21 -0400
On Tuesday, May 6, 2003, at 02:14 US/Eastern, Karl Goiser wrote:
G'Day,
I am having trouble with the stringWithUTF8String: method:
I am reading data from a file - UTF data - like this:
NSData * contentsData = [NSData dataWithContentsOfFile: pathName];
if (contentsData) {
contents = [NSString stringWithUTF8String: [contentsData
bytes]];
...
Intermittently, contents will return as nil. Well, actually, about
50% of the time! I can sit in ProjectBuilder, and hit command-R and
sometimes this routine will work and sometimes it will fail.
This is always on the same, unchanged file which is about 700 bytes
long.
Does anybody have any inkling why this might be so? It's got me!
stringWithUTF8String expects a NUL terminated string (i.e. the last
byte is a zero). Unless your file ends in a zero byte (which is
unlikely, if it is just text), then stringWithUTF8String: won't know
where to stop, and will run off the end of your data. When it does
this, three things can happen (in order of likelihood):
1) It eventually finds a sequence of bytes that are invalid UTF-8, in
which case it'll return nil
2) It eventually finds a byte with a zero value, in which case, it
succeeds (but may have garbage characters at the end)
3) It doesn't find either, and eventually runns out of your process'
membry space, and your program crashes.
Change your code to one of the following:
NSData * contentsData = [NSData dataWithContentsOfFile: pathName];
if (contentsData) {
contents = [[[NSString alloc] initWithData: contentsData
encoding: NSUTF8StringEncoding];
--
http://homepage.mac.com/clarkcox3/
email@hidden
Clark S. Cox, III
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.