views:

80

answers:

2

This one is weird. Hopefully I will ask the right question:

I'm using an md5 method to create a checksum value which I then write to a file. Then afterwards I read the file using this:

NSString * id_From_File = [[NSString alloc]
                                  initWithContentsOfFile:path_to_ID
                                  encoding:NSUTF8StringEncoding
                                  error:&error];

The result gets placed in a NSString which when I print gives me very strange behaviour. For example when I use this to print,

id_with_date = [NSString stringWithFormat:@"  %@  %@", dateString, id_From_File];

it will print both strings if dateString is placed in the first parameter and id_From_File in the second. If I switch them around (which I need to do) only id_From_File shows.

Edit 1: Example of the switch:

id_with_date = [NSString stringWithFormat:@" %@  %@", id_From_File, dateString];

I strongly believe this has something to do with the encoding of the id_From_File string.

Any knowledge!?

Thanks,

A: 

I've solved the problem!

It has to do with the fact that some strings use a null character to identify the end. Allow me to explain:

Lets say you have two strings, one with a null character at the end and one that doesn't. Depending on which way you order them, they will be read differently when concatenated.

 "somestring(null char)" + "another string"

The above, in some code, will read

 somestring

if places are switched

 "another string" + "somestring(null char)"

then you get

"another string somestring"

My simple hack to fix this was to make a new string with a substring of "some string" which easily got rid of that last char that was causing the bug.

I hope this is clear and helpful!

Eric Brotto
I hope you're using `+` as shorthand and not saying that you've been performing your Objective-C string concatenation with it? Because that won't do string concatenation, it'll do pointer arithmetic.
Jonathan Grynspan
Yes, it's shorthand. But nice job pointing that out!
Eric Brotto
Eric Brotto: The real question is why you're writing a null character into the file in the first place.
Peter Hosey
Peter Hosey: Good point!
Eric Brotto
+1  A: 

NSString should actually be capable of recognizing null characters as the file ending. Did you try to use a different method to load the string. I'd go for this one instead:

- (id)initWithContentsOfFile:(NSString *)path usedEncoding:(NSStringEncoding *)enc error:(NSError **)error

This method automatically detects the file's encoding instead of decoding it with a fixed one.

Max Seelemann