Battle of the String

This is a post about NSBundle’s pathForResource. My code pseudo-randomly selects between 3 “banners,” which are HTML files inside my project.

There are some battles worth fighting, I have found, and some not. Maybe on a rainy day I will figure out why this works:

int whichBanner = (arc4random() %3) + 1; // random 1 to 3
DLog(@"selected banner *%d*", whichBanner) // a formatted NSLog defined inside #ifdef debug
NSString *bannerPathString = @"FloracleBanner"; // starts the string
NSString *filePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"FloracleBanner%d", whichBanner] ofType:@"html"];
// previous line: gets pathForResource and appends "whichBanner" to string all in one line
DLog(@"filePath constructed is *%@*", filePath) // logs "/convoluted-path/FloracleBanner3.html" etc as it should

…And yet this does not:

int whichBanner = (arc4random() %3) + 1; // random 1 to 3
DLog(@"selected banner *%d*", whichBanner) // tests OK so far
NSString *bannerPathString = @"FloracleBanner"; // starts the string
bannerPathString = [bannerPathString stringByAppendingFormat:@"%d", whichBanner]; //appends whichBanner to the string, with (presumably) same result as the working method
DLog(@"determined filename for banner before extension is *%@*", bannerPathString) // and to confirm that, this tests just fine, with no hidden spaces or linebreaks (that's why I surrounded it with asterisks...) value is something like "FloracleBanner2"
NSString *filePath = [[NSBundle mainBundle] pathForResource:bannerPathString ofType:@"html"];
DLog(@"filePath constructed is *%@*", filePath) // logs filePath is *null* ... well, Hell.

So, both appear to be doing the same thing, yet only the first way works. There is probably someone who can explain this. I can not, nor have I found an explanation. My solution is to use the shorter, slightly-less-explicit version and move on.

This entry was posted in Uncategorized. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>