Search code examples
iosnsstringstringwithformat

NSStringWithFormat Crash


Simply stated, the following code has me baffled as to why it should fail.

// This line works
NSString * string = [NSString stringWithFormat:@"%lu",[[NSDate date] timeIntervalSince1970]];

// This line works
string = [NSString stringWithFormat:@"%@",@"somestring"];

// This line generates and EXEC_BAD_ACCESS error
string = [NSString stringWithFormat:@"%lu%@",[[NSDate date] timeIntervalSince1970],@"somestring"];

Why?


Solution

  • Value returned by [[NSDate date] timeIntervalSince1970] is of type NSTimeInterval which is of type typedef double NSTimeInterval; you are printing unsigned int. Replace @"%lu%@" with @"%f%@" and will be ok.