wayne
wayne

Reputation: 439

stringWithFormat Bad Access error

Can anyone explain why this code works perfectly:

int thumbnailPrefix = trunc([newGraph.dateCreated timeIntervalSinceReferenceDate]);

newGraph.thumbnailImageName = [NSString stringWithFormat:@"%d.%@",thumbnailPrefix,@"png"];

But this code causes a Bad Access error?

newGraph.thumbnailImageName = [NSString stringWithFormat:@"%d.%@",trunc([newGraph.dateCreated timeIntervalSinceReferenceDate]),@"png"];

Upvotes: 0

Views: 1044

Answers (2)

NWCoder
NWCoder

Reputation: 5266

trunc returns a double, not an int.

double trunc(double x);

So in the first code block you are converting it to an int, and correctly using the %d format specifier.

In the second, it should be an %f, or have (int) in front of it.

newGraph.thumbnailImageName = [NSString stringWithFormat:@"%d.%@",(int)trunc([newGraph.dateCreated timeIntervalSinceReferenceDate]),@"png"];

Upvotes: 2

Simon
Simon

Reputation: 9021

Have you tried typecasting the return from trunk() like....

newGraph.thumbnailImageName = [NSString stringWithFormat:@"%d.%@",(int)trunc([newGraph.dateCreated timeIntervalSinceReferenceDate]),@"png"];

It's a shot in the dark, but I expect NSString doesn't know the return type for the function trunc.

Upvotes: 0

Related Questions