Better shadow performance on views
There are two different uses for the shadowPath
property on CALayer
:
- Improving the performance of having a shadow
- Creating shadows that don’t match the contents of the view. Check out Apple’s Using Shadow Path for Special Effects.
For performance reasons, always set a shadowPath
. This is a substantial improvement, especially if the view changes position via animation or presence in a scroll view.
When you can set a path
The shadowPath
tells the system what should be casting a shadow without having to look at the contents of the view itself. Since most views that need a shadow are opaque, we just need to describe the appearance of the background of the view.
Using the convenience initializers on UIBezierPath
we can create ovals, squares and rounded rectangles without difficulty. For more complicated paths, check out A Primer on Bézier Curves. You can still use UIBezierPath
or CGPath
to create them, but it will require more complicated math.
Starting with a simple, purple view with a shadow:
let purpleView = UIView()
purpleView.backgroundColor = .purple
purpleView.layer.shadowRadius = 10.0
purpleView.layer.shadowColor = UIColor.black.cgColor
purpleView.layer.shadowOffset = CGSize()
purpleView.layer.shadowOpacity = 0.8
We can tell the system to draw a shadow for the entire square:
purpleView.layer.shadowPath = UIBezierPath(rect: purpleView.bounds).cgPath
For rounded corners, we can set the cornerRadius
property on the layer, and create a matching shadowPath
:
purpleView.layer.cornerRadius = 16.0
purpleView.layer.shadowPath = UIBezierPath(roundedRect: view.bounds, cornerRadius: 16.0).cgPath
When you can’t set a path
Sometimes it’s not possible to set a path because there’s no easy way to describe the contents of the view. For example, text is a mess of random contents. Rasterizing the layer avoids having to draw the shadow repeatedly.
// create our label
let label = UILabel()
label.textColor = .purple
label.text = NSLocalizedString("Swift Lemma!", comment: "")
label.layer.shadowOpacity = 0.6
label.layer.shadowColor = UIColor.black.cgColor
label.layer.shadowOffset = CGSize(width: 0, height: 2)
// render and cache the layer
label.layer.shouldRasterize = true
// make sure the cache is retina (the default is 1.0)
label.layer.rasterizationScale = UIScreen.main.scale
This produces a view that looks like this:
Keep in mind
Always set the shadowPath
inside either layoutSubviews()
or viewDidLayoutSubviews()
. Since Auto Layout likely means there aren’t constant sizes for views, setting a shadowPath
elsewhere may become outdated or incorrect.
When creating a path, the coordinate system for the path is the layer it’s applied to. To make it easier, pretend the shadow path is a subview. For this reason, we use the bounds of the view to create its shadow path.
Layout margins within a UIStackView
The UIStackView
property isLayoutMarginsRelativeArrangement
allows insets similar to margin constraints on subviews in a UIView
.
Let’s consider a simple single-subview example:
let containedView = UIView()
containedView.backgroundColor = .purple
let stackView = UIStackView()
stackView.addArrangedSubview(containedView)
You can then configure directionalLayoutMargins
and enable them like so:
stackView.directionalLayoutMargins = NSDirectionalEdgeInsets(
top: 8,
leading: 8,
bottom: 8,
trailing: 8
)
stackView.isLayoutMarginsRelativeArrangement = true
This is what it looks like, before and after:
ICANN created a history project documenting its formation nineteen years ago. I’m captivated by the interviews: corralling support and preventing disputes between so many interests seems like an impossible task. I couldn’t imagine the current political climate would come close to breaking something away from the US government with such bipartisan support. Their policies are downright ridiculous at times, but their history is certainly rich.
Is using a generic top-level domain a good idea?
I’ve been thinking about switching over my website and email to one of the new top-level domains. This has lead me to investigating what the switch would feel like, and how stable the move would be.
Will it survive?
I am looking at the .engineer
gTLD now owned by Donuts. At the time of writing this, there are a total of 2706 registered domains since late 2014. That’s nothing.
That got me thinking: what exactly happens when a gTLD fails?
The answers aren’t clear. When applying, ICANN requires registrars put up cash in the form of a bond to cover operational costs for 3 years. If a registrar were to fail, another can propose to take over. Their database is stored off-site, and data can be migrated.
But what if nobody does? What happens to a gTLD if there’s not enough domains to stay in business? The answer, it seems, is that the domain ends. There’s no provisions at ICANN to maintain domains beyond the transfer procedure.
Donuts, for what it’s worth, has stated they would not shut any down:
We think of all the TLDs as one big registry. It[’]s profitable, so all our TLDs are profitable, but that is beside the point. We’d no more shut down one of our TLDs than you would shut down 100 “unprofitable” second-level names in .link.
There’s definitely risk, and that’s not what the internet needs. It should be that, regardless of the fate of any registrar, a domain you purchase today will be valid as long as you renew it.
As an email
Generic top-level domains have been available for registration since 2013, but there’s a number of services that can’t handle them. I’m surprised how many times I enter one into an email field and see “invalid address” as the result.
The responses I’ve received are generally the “doing it wrong” variety and not the “I’ve filed an issue and we’ll look into it.” I’m not sure what I expected to be honest; I hoped that it would be passed up the food chain, but it always dies in the first round of support.
This means, to use a gTLD, I need to keep a backup domain for services like AT&T, CBS, Virgin Airlines, and Crunchyroll. I expected that in 2017 it wouldn’t be a problem, and for the most part it isn’t an issue. It’s frustrating though.
Premium domains
New.net tried replacing ICANN’s authority in the past, long before gTLDs existed. They offered some snazzy options, and I grabbed zac.tech
to play around. It didn’t work on most ISPs, but it did work on mine.
That’s a valid gTLD now! I could register it again! For the low, low cost of $2800. Per year.
This notion of a premium domain name is a money-grab by registrars. What constitutes a “premium” domain is arbitrary: length, dictionary words, prettiness, etc. If you try to register one of these domains at NearlyFreeSpeech you get a perfectly correct error:
This means the registry of this gTLD plans to extort extra money from anyone who wants this domain.
It is, and they do. These premium prices may come down. Perhaps they’ll stop charging extra to renew them entirely. But when your registry has a few thousand total domains are premium bottlenecks the right way to go about this?
The future?
I’m worried that entire namespaces are being taken by companies for their internal use, like Google seems to be doing with .dev
. If you’ve got the cash, you can take complete, even dictatorial, ownership. That’s not how existing domains worked, but it’s the rules we’re living under with ICANN’s leadership.
But we can’t continue to have one namespace. We’ve been in a world where everything but .com
was wrong, and Verisign’s control over it has been harsh. These new top-level domains are nicer looking and there’s significantly more availability.
So I’m thinking about switching. There’s a lot to choose from, and more opening up every day. I’m on a ccTLD right now, and there’s a real risk that it could go away at any time through local laws or disputes. Remember when every startup was using Libya’s .ly
domain?
Generic top-level domains feel like an improvement for the internet as a whole. The cruft at the end doesn’t have to be cruft; it can be descriptive, it can be helpful, and above all it can be nice.
Libby is a nice way to browse the San Francisco Public Library’s collection of eBooks and audiobooks. It has a lot of rough edges. It makes up for it with the send-to-Kindle feature so I can read borrowed books on a proper screen.
How Apple explains audio session prioritization, from Activating an Audio Session:
I did not expect a comic when I clicked on the documentation link.
In Apple’s latest The Rock x Siri advertisement you can hear the Wilhelm Scream at 2m43s. After the episode of Twenty Thousand Hertz about its backstory, it’s hard not to find it everywhere.
Age of Swords comes out next week, but that didn’t stop this Barnes & Noble from putting it out early. If I were willing to go non-digital I’d be reading it right now.
I’m looking forward to Iron Gold. It’s the fourth book of the Red Rising series which explores distant future humans splintered into sub-groups with one dominant over the solar system.
Personal names around the world explains the complication of names. The biggest take away: ask users for their full name and short name. Don’t try and parse out first names or separate first and last into separate fields.
Butterick’s Practical Typography has recommendations and pointers about laying out and writing copy. The ranking of system fonts is especially useful. Love the dislike of title case in headings.
Vault 11 in the game Fallout: New Vegas contains an interesting experiment: how would people react if an authority tells them to sacrifice one of their own? Oxhorn examines the vault and draws parallels to the Milgram experiment. Excellent worldbuilding.
I’ve been listening to The History of English Podcast. It’s not easy to binge but it’s a mainstay in my weekly podcast rotation. I’m currently around the fall of the Roman Empire. It’s fascinating that our alphabet has bounced between cultures but with only minor changes.
Automating iOS app builds
I believe an important part of the development process is getting a working version into the hands of others. As part of this, being able to install the latest and greatest on the fly is paramount. It took me a lot of time to find a reliable way to build, sign, and distribute apps as part of this internal continuous delivery.
I do not recommend running your own build machines. Wasted days with Jenkins failing and Xcode crashing have taught me this is the most fragile part—and worth outsourcing. Fortunately, there are now companies dedicated to it. CircleCI has served me well: their support is fantastic and their service, despite the beta label, is very reliable. You might need to send them a quick message to request access.
Below is the outline of creating a script to generate builds. My goal isn’t to create a file you can copy-and-paste, rather to describe the methodology. If you want a full solution, I hear good things about fastlane.
Configure deployment
To instruct CircleCI to run a distribution script, add a deployment step like the following to your circle.yml
file. You can find more information in the CircleCI iOS docs.
machine:
xcode:
version: 6.3.1 # We want nullability, etc.
deployment:
s3:
branch: /.*/ # All branches
commands:
- ./your-directory/your-script.sh | tee $CIRCLE_ARTIFACTS/distribute.log:
timeout: 600
I like to log the build verbosely, so I save the entire transcript as an artifact. This makes it a lot easier to find compile issues. Note the timeout key is indented another level below the script command, which is a key itself. YAML syntax is strange.
Create a keychain
The most complicated part is handling your signing credentials. I’ve found that the simplest and most secure solution is a keychain checked into the repository. To store your private key and Apple-signed certificate, let’s create one:
- Launch Keychain Access (inside your Utilities folder).
- In the “File” menu, choose “New Keychain” and note the secure password you use.
- From your “login” keychain, locate and select both:
- Your distribution certificate—the one from Apple.
- Your private key, which you generated, likely a sub-item.
- Copy the two items to your new keychain by holding Option (⌥) and dragging them into the keychain.
Using a keychain directly allows Xcode’s tools access to your credentials. It’s also easy to update: just repeat the above steps with your existing keychain after renewing your certificate. You can include as many signing identities as you wish in the same keychain: enterprise, ad-hoc, App Store, etc.
Use the keychain to codesign builds
Create an environmental variable (here named IOS_CI_KEYCHAIN_PASSWORD
) with the password you created above. Don’t store this within your repository.
Command-line operations require absolute paths to the keychain file, so we need to save that into a variable. This example assumes you’re executing a script in the same directory as the keychain:
# Make any command erroring fail the whole script
set -e
# Get the absolute keychain path - `security` requires absolute paths
pushd $(dirname $0)
TOOLS_PATH=$(pwd)
popd
KEYCHAIN_NAME="$TOOLS_PATH/distribute.keychain"
With our keychain’s absolute location, we can now:
- Tell the system to use our keychain, and
- Use the password environmental variable to unlock our keychain.
Note: If you run the following locally, you will lose access to your keychain. To fix it, instead use the absolute path to $HOME/Library/Keychains/login.keychain
.
# Set our keychain as the search path. Don't run this locally.
security list-keychains -s "$KEYCHAIN_NAME"
# Unlock it using the environmental variable.
security unlock-keychain -p "$IOS_CI_KEYCHAIN_PASSWORD" "$KEYCHAIN_NAME"
# Make sure we have a long timeout window.
security set-keychain-settings -t 3600 -u "$KEYCHAIN_NAME"
function cleanup {
# Clean up on any kind of exit, just in case something bad happens.
echo "Cleaning up keychain due to exit"
security lock-keychain -a
}
trap cleanup EXIT
When run, your commands will have access to your certificates and keys until the script exits cleanly or otherwise.
Copy provisioning profiles
You will also need the provisioning profiles you’ve configured in Xcode. For simplicity’s sake, don’t bother figuring out which; just copy everything into your repository.
PROVISIONING_SYSTEM="$HOME/Library/MobileDevice/Provisioning Profiles/"
PROVISIONING_LOCAL="$TOOLS_PATH/provisioning-profiles/"
mkdir -p "$PROVISIONING_SYSTEM"
find "$PROVISIONING_LOCAL" -type f -exec cp '{}' "$PROVISIONING_SYSTEM" \;
You can add an rm -rf "$PROVISIONING_SYSTEM"
to the cleanup function as well.
Create and upload the build
Building .ipa
files is unnecessarily hard. I don’t know why. I use Nomad, which cleanly wraps the somewhat-private Xcode commands.
Nomad supports many upload destinations and services; for file storage, I like to use S3. Its library uses AWS_ACCESS_KEY_ID
and AWS_SECRET_ACCESS_KEY
environmental variables, which you should create as a new limited-access IAM user.
# Where to store the IPA. CircleCI has an artifacts folder you can stuff things into.
# Some other providers seem to lack this, so perhaps use /tmp/.
IPA_NAME="$CIRCLE_ARTIFACTS/$CIRCLE_BRANCH.ipa"
# Disable archive because otherwise it will build twice, wasting time.
# If you aren't using Bundler (you should, though), drop the `bundle exec` part.
bundle exec ipa build --no-archive --verbose --ipa "$IPA_NAME"
bundle exec ipa distribute:s3 -b "your-bucket-name" -f "$IPA_NAME"
You may also use Nomad to upload additional files like the dSYM to your crash reporting service, metadata like the latest build number from agvtool
, or certain branches directly to iTunes Connect.
Install on device
Name files by branch. This makes testing somebody’s idea or feature extremely easy. The iOS Deployment Reference gives you all you need to get started. Basically, you need an itms://
link pointing to a .plist
file pointing to the .ipa
file. It’s quite easy.
Localizing attributed strings on iOS
In an iOS app, localization can be especially difficult when dealing with attributed strings. Fairly often, designers request something like:
Read our Terms of Service, Privacy Policy, or contact us with any questions.
or like:
Searching for burgers in SOMA, San Francisco, CA:
The golden rule of localized strings is to treat them as atomic units:
- Never concatenate strings to form sentences. Many languages have different sentence structure or gender rules than English and you cannot just substitute a single word or phrase in for any other.
- Never use substrings for searching in an original string. If you depend on the standalone translation of “Privacy Policy” matching the sentence version, you will likely find translators do not understand this intent. You may also find the same search term multiple times (imagine if the user searched for “Search”).
Often these complexities are cited as reasons to avoid localization. But, unless you have geographic constraints, you will find a substantially larger audience with a localized application.
ZSWTappableLabel and ZSWTaggedString are two open-source libraries I have released to help solve these problems.
ZSWTappableLabel makes links inside your attributed strings tappable, as the name suggests. It’s a UILabel subclass which does not do any drawing itself, making it fast and easy.
ZSWTaggedString is the powerhouse. It transforms an HTML-like syntax into an attributed string. You can read more about the syntax and advanced usage on its GitHub page, but here’s how you might use it for the examples above:
Read our <i><tos>Terms of Service</tos></i>, <i><privacy>Privacy Policy</privacy></i>, or <i><contact>contact us</contact></i> with any questions.
Searching for <term>%@</term> in <location>%@</location>:
In my experience, localizers1 are familiar enough with HTML to have no issues with localizing these strings. By marking the regions you intend to be visually distinct, they can more easily understand your intent, producing better localizations.
While on the subject, here are a few best practices for localization in iOS:
- To handle the current locale changing, or the dynamic type setting changing, reload your UI when observing:
NSCurrentLocaleDidChangeNotification
UIContentSizeCategoryDidChangeNotification
- To represent dates, durations, distances, lengths, etc., use an appropriate formatter.
- To create your own date formats, use
+dateFormatFromTemplate:options:locale:
on NSDateFormatter. Remember that these need recreating if the locale changes. - To combine a first and last name, use
ABPersonGetCompositeNameFormatForRecord
with a temporaryABPersonRef
, or use the newNSPersonNameComponentsFormatter
. - For sending non-user-facing data to a server, use
en_US_POSIX
as your locale.
Read more tips and tricks at NSHipster about NSLocalizedString and NSLocale.
T-Mobile: good ideas, bad experience
When T-Mobile entered the wireless scene as the “Uncarrier” I was impressed. Their greatest contribution to the carrier ecosystem is consistently adding features, forcing other carriers to keep up. Instead of rationed text and voice, we’re in a world where data is king.
However, if you are considering T-Mobile service, I suggest reconsidering. The plans and features look appetizing, but their execution leaves a lot to be desired. I would not count on their unique features; just the now-basics with worse coverage.
I wrote off my initial experiences as anecdotal, but it became cumulatively enough for me to leave their service.
Free data for life on tablets
My first experience with the new T-Mobile was their offer of free monthly 200mb of data. It’s a compelling reason to go with them.
After a month of lifetime free data, it ended and I got “could not connect to data service” errors. The first rep I spoke with ran me through the usual steps culminating in toggling something on his side and waiting 48 hours to see if it worked.
The next rep a couple days later insisted I had to reformat without restoring a backup. This was a huge pain, and unsurprisingly didn’t fix anything. He filed a report with “the engineers.”
A few more days later, service started working again, and later the rep called to make sure. The follow-up made me happy, despite the length of time from start to finish.
Update 2014-12-29: After moving my cell phone from T-Mobile to AT&T, I started receiving a bill for $10/mo for my “free data for life” device. I called and received a credit the first time, but dug into it more the second time.
Their retention department informed me that the “free data for life” offer requires having another device with T-Mobile service. According to their press release (backup) no such qualifier existed when I signed up, and according to their second press release (backup) “there is no $10.00 per month fee for the 200MB of free data.”
I see no qualifiers on their support page so I can only assume their screw-the-customer attitude is behind-the-scenes policy.
Refer-a-friend bonus
There’s no zealot like a convert, and I convinced a few friends to switch their service over. When T-Mobile announced a new referral system, wherein both sides get unlimited data for a year, my latest referral and I signed up.
I received only a $25 in-store gift card, and waited a few weeks to call the refer-a-friend support to figure out why. I was immediately told it was a mistake, and the rep said he would add unlimited data to my plan.
I asked for clarification on the change, and he confirmed it was “free for 12 months,” and suggested my friend call, too. Another rep added unlimited data to my friend’s account.
Not-so-bonus
My bill went up by $50, or $20 more than just adding unlimited data would cost. My friend’s bill went up, too.
When I called support, the first rep clarified that my referral would only give me a $10 discount on unlimited service. After expressing confusion, she placed me on hold to ask refer-a-friend support.
The phone rang, and I was greeted with, “T-Mobile refer-a-friend support, how can I help you?” I was blindly transferred, and had to explain everything for the second time.
This rep said a few things, and I got the impression he believed I added unlimited data myself:
- I had 2 referrals, one processed (the gift card) and one pending (a few days old).
- Referral #1 was activated a few days before the data offer started, and didn’t qualify.
- Referral #2 would give me a $10 discount on my existing unlimited data.
- If I ended my existing unlimited data, referral #2 would be nullified.
- No refer-a-friend rep would have added unlimited data to my account.
The net result is I would have to pay $20 extra monthly to get unlimited data, which should have been free twice over. I asked him to take off the unlimited data charge, and he placed me on hold.
And then I heard, “all of our representatives are busy, please hold,” and got to explain everything again to a third rep I was blindly transferred to. This final rep was nice enough to credit the plan and remove unlimited data from my account, at least, even though she accidentally hung up on me towards the end.
I complained about this on Twitter and although their Twitter presence contacted me, they never responded days after asking for my phone number.1
Free texting in the air
I had the opportunity to give another new benefit a try: on Gogo in-flight internet, devices already set up for WiFi calling can connect to the network for SMS service. This did not work.
When it came time to “get started” on the T-Mobile side of things, I received errors repeatedly and I gave up. Gogo support was nice enough to credit a free hour of internet for my troubles, which is a fine example of what I’m really looking for: solutions.
Goodbye
T-Mobile is a noble experiment executed with good intentions but badly in need of restructuring. Every time I try a perk, it backfires, and I don’t care to spend hours fighting.
I am switching to AT&T to pay the same amount. If there’s one good thing T-Mobile is doing, it’s pushing the other carriers to offer competitive plans. However, issues with implementation make their poor coverage feel even worse. Hopefully this changes in the years to come.
-
I dislike that Twitter direct messages require following the sender. I gave up after a few days because I was tired of seeing their tweets, so perhaps they tried to respond some time later. I doubt it. ↩︎
Enabling bridge mode on AT&T U-verse
These are instructions to configure a U-verse gateway to send all of its incoming traffic to your own router without impacting its normal networking services.
The gateway
The gateway model that I am using is a 2Wire/Pace 3800HGV-B, but these instructions likely work for similar models.
You can connect to it at 192.168.1.254
. This service is abysmally slow and fairly hard to navigate as a result. The gateway will on occasion prompt for the password labeled “system password” on its serial number sticker.
Turning on DMZplus
First, we need to forward all of the traffic to the router. This can be done as follows:
- From the gateway, navigate to:
Settings
>Firewall
>Applications, Pinholes and DMZ
. - Choose the router from the list. It will appear as a link named “Choose <name>.”
- Change its setting below to “Allow all applications (DMZplus mode).”
Assigning a public IP
Finally, we need to give the router the knowledge that it’s a public-facing device. UPnP and NAT-PMP rely on determining the public IP, and having the correct WAN IP is required for many routers.
We can achieve this by assigning the router the public IP address as follows:
- Navigate to
Settings
>LAN
>IP Address Allocation
. - Locate the settings box for the router.
- Change its “Address Assignment” from “Private” to “Public.”
All done
After the router renews its DHCP lease, it will be assigned the public IP address. This is generally a huge button labeled “Renew DHCP Lease” or a power cable plugged into the device.
U-verse IP addresses are dynamic, but are deterministic from hardware configurations on their end. Thankfully, this means the addresses very rarely change. I’ve gotten away with just adding an A
record to a random domain name to make it easy to access my VPN.
Saving optimal JPEGs on iOS
Conventional wisdom for creating a JPEG version of a UIImage
is first to turn it into an NSData
and immediately write it to disk like so:
NSData *jpegRepresentation = UIImageJPEGRepresentation(image, 0.94);
[jpegRepresentation writeToFile:outputURL.path
atomically:NO];
Most of the time this is exactly right. However, if file size is important, Image IO is a great alternative. It is a powerful system framework to read and write images, and produces smaller files at the same compression level.
Why Image IO?
A project I am working on requires uploading photos en masse. Low upload bandwidth makes file size a limiting factor, so I sought out ways to reduce it.
I put together a test project to find the differences between the two methods. The results are pretty interesting:
- Image IO files are on average 20% (but up to 30%) smaller1.
- Image IO takes about 2x longer.
The only discernible visual difference is the grain in the images, but even that is minor. Here’s a diff between two versions of the same original photo:
Using Image IO
First, you’ll need to add two new framework dependencies:
@import ImageIO; // to do the actual work
@import MobileCoreServices; // for the type defines
When creating your JPEG file, the first step is to create a CGImageDestinationRef
specifying where to write the result:
CGImageDestinationRef destinationRef =
CGImageDestinationCreateWithURL((__bridge CFURLRef)outputURL,
/* file type */ kUTTypeJPEG,
/* number of images */ 1,
/* reserved */ NULL);
Image IO is able to produce files of a few different types2 but my focus here is JPEGs. Next, we set up the properties of the output file, specifying a constant compression factor:
NSDictionary *properties = @{
(__bridge NSString *)kCGImageDestinationLossyCompressionQuality: @(0.94)
};
CGImageDestinationSetProperties(destinationRef,
(__bridge CFDictionaryRef)properties);
And, importantly, we specify what is to be written out:
CGImageDestinationAddImage(destinationRef,
/* image */ image.CGImage,
/* properties */ NULL);
And finally, we write it to disk and clean up the reference:
CGImageDestinationFinalize(destinationRef);
CFRelease(destinationRef);
-
The UIImage version has a color profile, while the Image IO version does not. However, running both files through Image Optim produces a 7% reduction on both, so I am choosing to ignore this difference. Afterall, you can’t remove the color profile anyway! ↩︎
-
The following are possible types you can use, from the documentation:
Constant UTI type kUTTypeImage
public.image kUTTypePNG
public.png kUTTypeJPEG
public.jpeg kUTTypeJPEG2000
public.jpeg-2000 (OS X only) kUTTypeTIFF
public.tiff kUTTypePICT
com.apple.pict (OS X only) kUTTypeGIF
com.compuserve.gif
Using the Xcode Structure menu
Xcode’s Editor > Structure menu has a few great actions:
These actions all act on either your cursor position or selection.
Balance Delimiter
Normally you can double-click quotes, brackets, or parenthesis to select the matching character and all text in-between. The Balance Delimiter behaves similarly: it looks at your cursor position (or selection), finds the nearest pair and selects in-between.
This doesn’t have a default keyboard shortcut, but you can set one up in Xcode’s Key Bindings preferences. I set it to ⇧⌃I
since I use it in similar ways to Re-Indent.
Re-Indent ⌃I
Objective-C is a fairly indentation-heavy language, and Xcode generally does a good job at indenting while you’re typing. However, if you’re pasting text or refactoring things can get pretty hairy, so let Xcode fix up your code for you with Re-Indent.
Shift Left ⌘[
, Shift Right ⌘]
You can also indent manually using the Shift Left and Shift Right actions, which unindent or indent by one tab, respectively. They do exactly what they say on the tin.
Move Line Up ⌥⌘[
, Move Line Down ⌥⌘]
These actions move your current line (or selection) up or down by one line. Simple, right? What’s really useful is that it is context-aware: they understand going in and out of control flow or blocks. Much faster than cutting, pasting and re-indenting each time.
Comment Selection ⌘/
Rather than wrapping your code in /* … */
and dealing with the conflicting multi-line comments you probably already have, simply select what you want to temporarily eliminate and hit the shortcut. Each line selected is then prefixed by //
.