Ternary operator

Ternary operators are a concise way to write conditional statements that have two possible outcomes. Rather than writing a longer series of if/then/else statements you can write one line that makes it clear what the two choices are.

In this example from iOS, I use a string for direction—either clockwise or counterclockwise—and translate it to a number for use in the formula. That way I don’t have to remember whether -1 is clockwise or counterclockwise when calling the method. I can use natural language to call the method and let the ternary operator take care of the conversion to the value I need in my formula. And I can change my formula at a later date without having to go back and find all the method calls.

Here’s the method call and the operator


- (void)spin:(NSString *)direction withDuration:(float)duration withScale:(float)scale {
    
    int rotation = ([direction isEqualToString:@"clockWise"] ? 1 : -1);

And then use rotation later to determine which way the object rotates


view.transform = CGAffineTransformRotate(CGAffineTransformScale(transform, 1.0, 1.0), rotation * 2*M_PI/3);

Here’s another example, where I want to pass in a value, but make sure that it isn’t less than one. In this case I’m passing in an integer and rather than doing a series of complicated if/then/else statements I just put the ternary operator in where the integer goes.


self.showRewards = [[ShowRewards alloc] initWithParentView:self.view withLevel:(rewardLevel > 0 ? rewardLevel : 1) ];

I also use it in PHP code for plurals. Something like this is what I use.

$text = "The update was successful. $recordsUpdated " . ($recordsUpdated > 1 ? 'records were updated.' : 'record was updated.');
echo $text;

And I use it to write one set of code that works for two inputs. In this case I have a page that displays all of the titles that are downloadable from Gumroad. Since people are only interested in the Mac or Windows version, I put them on two different pages—but I use the same code. The first part reads in the page type from the URL and puts up a title for Macintosh or Windows.


if ( isset($_GET['page']) ) { $MacWin  = mysql_real_escape_string($_GET['page']); }  else { $MacWin  = 'Win';} 

echo "<div id='wideMargins'>";
$MacintoshWindows = ($MacWin == 'Mac' ? 'Macintosh' : 'Windows');
echo "<h2 class='NewSection'>Download $MacintoshWindows Compatible Titles from Gumroad</h2>";

Then in the SQL statements I pull the appropriate titles. My column names are GumroadURL_Mac and GumroadURL_Win so the $MacWin variable is substituted into the SELECT statement.


$qry = "SELECT *
        FROM product, product_instance
        WHERE product.id = product_id
        AND GumroadURL_$MacWin IS NOT NULL
        ORDER BY name";

I use a full ternary operator to get the right column from the row.


for ($i = 0; $i < $numRows; $i++) {
    $row   = $res->fetch_array();
    $name = $row['name'];
    $tagline = $row['tagline'];
    $GumroadURL = ($MacWin == 'Mac' ? $row['GumroadURL_Mac'] :$row['GumroadURL_Win']);

As you can see, it makes the code much easier to read and in this example, I have one page of code that easily generates two web pages.

Make a file invisible.

On Unix-like systems (e.g. Linux and OSX) you can make a file invisible with the following command:
setFile -a V /Users/userid/Desktop/untitled\ folder

To make it visible again, just change the V to a lower case v.
setFile -a v /Users/userid/Desktop/untitled\ folder

In this example, from OSX, I typed setFile -a V and then dragged a folder from the desktop to the command line. userid is really my userid. Unless you changed it, it is the same as your command prompt i.e userid$. It’s a bit harder to make a file visible, since you can’t drag it in from the finder.

break;

This is another programming tool that I don’t recall ever using before. Normally in a loop I cycle through the elements and do something with each item. For example, this Objective C method loops through all the words in the shuffledWords array and returns a list of the words. The for loop in this case uses ‘fast enumeration’ to select each object in the array.


- (Word *)getAndOrButWord:(NSString *)group {
    Word *wordToReturn;
    for( Word *aWord in self.shuffledWords ) {
        if ( [group isEqual:aWord.group] ) {
            wordToReturn = aWord;
        }
    }
    return wordToReturn;
    
}

And this is part of a method that uses the more traditional for loop that explicitly loops through all of the items in an array.


for (NSInteger i = 0; i < [self.prefsCategory1 count]; i++) {
            if ( [[self.prefsCategory1 objectAtIndex:i] isEqualToString: @"1"]) {
                NSString *levelAndPart = [NSString stringWithFormat:@"PREFS01_NAME Part %i", i];
                [self.selectedCategories addObject:levelAndPart];
            }
        }

In both of these cases each item is looked at and appropriate action taken. However, you can break out of the loop early if you don’t need to look at each item. In this simplified example, I only need four items that match the criterion so there is no point in looping after I’ve found four.


for ( Word *gWord in wordsInGroup ) {
    [wordListToReturn addObject:gWord];
    if ( [wordListToReturn count] == 4 ) break;
}
NSLog(@"I've broken out of the loop");

Control goes out of the loop entirely, just as if all the items had been looked at.
Here is a real world example with multiple break statements. In this case I have an array of 200 objects (girls with colored backpacks) and I want four items from the array. The backpacks are colored and have a different colored stripe on them. In the game I ask the child to show me the backpack that is, for example, red and green. But I don’t want to display a green and red backpack on the screen since it would be confusing to the child. There are two breaks in this example. First I loop through the ‘wordListToReturn’ array to see if the backpack can be added. If it can’t then there is no point in looking at the rest of the items in the array so I break out. This takes me to the outer loop and I pick the next object in the backpack array. Once I get four items I don’t need to continue, so there is another break that takes me out of the loop entirely.


NSInteger wordsToReturnCount = 1;
    for ( Word *gWord in wordsInGroup ) {
        // Add the first item to the list
        if ( ![wordListToReturn lastObject]) {
            [wordListToReturn addObject:[wordsInGroup objectAtIndex:0]];
            NSLog(@"First Word added %@", [wordListToReturn objectAtIndex:0]);
        // Loop through after the first word in in the list
        } else {
            BOOL addWord = YES; // Assume you'll add the word unless there is a match
            NSLog(@"gword is %@", gWord.image);
            // Look through all the words in the return list and see if this word matches
            for ( Word *lWord in wordListToReturn) {
                NSArray *gWordColors =[NSArray arrayWithObjects:gWord.color1,   gWord.color2, nil];
                NSArray *lWordColors = [NSArray arrayWithObjects:lWord.color1, lWord.color2, nil];
                
                [gWordColors sortedArrayUsingSelector: @selector(caseInsensitiveCompare:)];
                [lWordColors sortedArrayUsingSelector: @selector(caseInsensitiveCompare:)];
                
                NSString *sortedgWordColors = [NSString stringWithFormat:@"%@ %@", [gWordColors objectAtIndex:0], [gWordColors objectAtIndex:1] ];
                NSString *sortedlWordColors = [NSString stringWithFormat:@"%@ %@", [lWordColors objectAtIndex:0], [lWordColors objectAtIndex:1] ];
                NSLog(@" gWord: %@, lWord %@", sortedgWordColors, sortedlWordColors);
                if ([sortedgWordColors isEqualToString:sortedlWordColors]) {
                    addWord = NO;
                    break;
                }
            }
            if (addWord) {
                [wordListToReturn addObject:gWord];
                NSLog(@"Word added");
                wordsToReturnCount++;
            }
            if (wordsToReturnCount == 4 ) break;
        }
    }

Updating apps in iOS – Icons for Retina Display

The Apple documents on icon sizes is a bit out of date. It does not include the icon for the new retina iPad. And it is not updated for the new 1024×1024 iTunesArtwork requirement.

You need to include a new file that is 144×144 pixels and call it ‘Icon-72@2x.png’.

Then add it to your icons list in the Info.plist file.

Since I have lots of apps, I edited the Info.plist files in BBEdit and cleaned out all of the old icon files. You can also edit them in XCode by right-clicking on the Info.plist and choosing ‘Open As-Source Code’. The original files had the icon information between the ${EXECUTABLE_NAME} and CFBundleIdentifier keys so the new file looks like this.


  <string>${EXECUTABLE_NAME}</string>
  <key>CFBundleIconFiles</key>
  <array>
  <string>Icon.png</string>
  <string>Icon@2x.png</string>
  <string>Icon-72.png</string>
  <string>Icon-72@2x.png</string>
  <string>Icon-Small-50.png</string>
  <string>Icon-Small.png</string>
  <string>Icon-Small@2x.png</string>
  </array>
  <key>CFBundleIdentifier</key>

XCode will use the files to populate the icon display in the summary view, so you can check to see if you did everything correctly. If no icon shows up, make sure they are associated with the app and then drag the icon to the appropriate empty place in the summary. You should get an error message telling you why the icon is not appropriate. Usually it’s a size issue. If it fills in the spot, you probably have a naming issue.

Icon is 57×57 and Icon-Small is 29×29. The rest are obvious from the naming convention. The rest of the sizes are listed in the document, referenced below, along with their intended use.

According to the Apple document Core Foundation Keys you shouldn’t append the .png extension so that the system will automatically use the @2x version when appropriate. However, this doesn’t work for me.

XCode 4.5 doesn’t support any version of iOS before 4.3 so do not use CFBundleIconFile.

You also need to include a file called iTunesArtwork and iTunesArtwork@2x (no .png extension) in your application bundle that are 512×512 and 1024×1024 pixels respectively. Do not list them in the Info.plist file.

Two posts with more info Jared Sinclair and Peter Levine

Updating apps in iOS – Retina Display

I have a bunch of small icons that I use in my apps and for all of them, I just doubled the size of the image and added @2x to the name. For most of the icons that was all I needed to do because the frame I created for the images was a fixed number of points. iOS scaled the images appropriately. For some images I determined the frame size by looking at the size of the image. For those images I had to divide by the scale factor or the images would be twice as big as I wanted. e.g.


CGFloat deviceScale = [UIScreen mainScreen].scale;
cButton.frame = CGRectMake(0, 0, cImage.size.width/deviceScale, cImage.size.height/deviceScale);

All of my games rely heavily on graphics and they are large—too large to include both a normal size and @2x version. I can get the device to display the images as if they were labeled @2x by a simple conversion.


if ([[Utilities deviceType] isEqual:@"iPhone Retina4"] || [[Utilities deviceType] isEqual:@"iPhone Retina35"] ) {
        pictLeft  = [UIImage imageWithCGImage:pictLeft.CGImage  scale:2 orientation:pictLeft.imageOrientation];
        pictRight = [UIImage imageWithCGImage:pictRight.CGImage scale:2 orientation:pictRight.imageOrientation];
    }

This works on the iPhone because the images are way bigger than they need to be. On the iPad they aren’t more than twice the number of pixels that are displayed, so it doesn’t work.