Under The Bridge Under The Bridge

Tag: Xcode
The Xth-Code Files: Xcode 10 Tips

Now that we’ve hopefully all got our iOS 12 and Swift 4.2 migrations under control, let’s catch our breath and dive a little deeper into what’s new since last year with Xcode 10, shall we? 

What’s New in Xcode

Dark Mode Interface and Mac App Support

  • All-new dark appearance throughout Xcode and Instruments
  • Asset catalogs add dark and light variants for custom colors and image assets
  • Interface Builder switches between dark and light previews of your interface
  • Debug your Mac apps in dark or light variants without changing OS settings

Source Control

  • Changes in the local repository or upstream on a shared server are highlighted directly within the editor…
  • Support for cloud-hosted and self-hosted Git server offerings from Atlassian Bitbucket, as well as GitLab to go along with existing GitHub support.
  • Xcode offers to rebase your changes when pulling the latest version of code from your repository.
  • SSH keys are generated if needed, and uploaded to service providers for you.

Editor Enhancements

  • Place multiple cursors in your code editor to make many changes at once.
  • Code folding ribbon can now hide any code block surrounded by braces.
  • Over-scroll makes it easy to center the last lines of code in the middle of your screen.

Playgrounds Built for Machine Learning

  • New REPL-like model reruns your existing playground code instantly.
  • Run your code up to any specific line, or type shift-return to run the code you just added.
  • Import the Create ML framework to interactively train new models, and then write code to test the model right in the playground. When finished, drag the model into your app.

Testing and Debugging

  • Debugging symbols are downloaded from a new device five times faster than before.
  • Xcode will spawn a collection of identical Simulators to take advantage of your multi-core Mac, and fan tests out to run in parallel, completing your test suite many times faster.
  • Run tests in random or linear order.
  • Instruments automatically show OSLog signposts you add into your code.
  • Build and share your own custom instruments package to provide unique data visualization and analysis for your own code.
  • Memory debugger uses a compact layout to make it easier to investigate your memory graph.
  • Metal shader debugger lets you easily inspect the execution of your vertex, fragment, compute, and tile shader code.
  • Metal dependency viewer provides a detailed graph of how resources are used in your Metal-based app.

Build Performance

  • New build system enabled by default with improved performance throughout.
  • Swift compiler builds each individual file significantly faster.
  • Large Swift projects build for debugging dramatically faster when using the incremental build setting.

That’s a pretty good selection of improvements, yes? And we have an admirably exhaustive collection of release notes to dig deeper:

Xcode 10 Release Notes

Interface Builder Release Notes for Xcode 10

Build System Release Notes for Xcode 10

Source Editor Release Notes for Xcode 10

Swift 4 .2 Release Notes for Xcode 10

So, we recommend you Read Them All! of course, but here let’s call out the things that you definitely don’t to overlook. #1 is your optimization flags:

If you’ve been around for a while, chances are you’ve set Whole Module Optimization for your project. This is now incorrect: it prevents incremental builds and those are faster. For the definitive word on that, see What’s New in Swift from WWDC 2018, at 11:40:

Stop Using Debug with Whole Module Compilation

Doesn’t get more explicit than that!

As well, there’s a new Build with Timing Summary action (or -buildWithTimingSummary flag to -xcodebuild) that will tell you exactly where all the time is going. There’s a pair of articles here that go into more detail on those and other goodies:

Enabling newly added opt-in features in Xcode 10

Build performance analysing in Xcode 10

#2, now that you’ve got the compilation flags settled, is how to parallelize your building as much as possible. There’s a new Parallelize Build option in your scheme’s build settings, and if it’s not checked, go check it. With some luck, it’ll all Just Work™, but if you have any code generating phases — we like R.swift, for instance — you’re going to find that parallelization isn’t going to work until you set the script file output filenames properly. This, and a good bit more, is explained in detail at

Improving Your Build Time in Xcode 10

#3 — speaking of parallelization — is that now your tests can be run in parallel, and randomized to boot, to make sure that you don’t have any implicit dependencies in your tests! Those are another couple optin checkboxes — for full details watch WWDC 2018’s What’s New in Testing, or check the notes at

WWDC 2018 What’s New in Testing Recap

That’s about it for the major active actions you need take to make your project Xcode 10 savvy, but there’s plenty more nuggets to dig up. For instance, exporting NSData easily:

Xcode 10 has a new QuickLook popover for (NS)Data. It now provides an “Export” feature that can be used to dump memory contents to a file. This is very convenient when you want to investigate data with external editors. (e.g. the fantastic HexFiend)

Also, you’ve no doubt noticed already that the Library is now its own window, and may have found its behaviour somewhat opaque — to keep it open by holding down Option, and some more power tips, check out

Xcode 10 Library Tips

Xcode 10 Storyboard Changes

And let’s not fail to not your annual reminder to clean your old Simulators:

$ xcrun simctl delete unavailable
$ rm -rf ~/Library/Developer/Xcode/iOS\ DeviceSupport/

That should free up at least a few gigs for you. 

Finally, if you’re really interested in digging into Xcode trivia deeper than “delete it whenever things start acting squirrely,” check out:

What’s inside the Derived Data folder?

UPDATES:

Unleashing the power of asset catalogs and bundles on iOS

Xcode & Instruments: Measuring Launch time, CPU Usage, Memory Leaks, Energy Impact and Frame Rate

Building an iOS App Without Xcode’s Build System

awesome-xcode-extensions: “Awesome native Xcode extensions.”

The hidden value of Xcode schemes

Xcode Environment Specific Configuration

Swift Four -point- One And All

Looks like a particularly Good Friday today: It’s iOS 11.3 Day, which means Xcode 9.3 Day, which means we have a new Swift to learn:

Swift 4.1 Released!

Swift 4.1 is now officially released! It contains updates to the core language, including more support for generics, new build options, as well as minor enhancements to Swift Package Manager and Foundation. There was also significant progress made in stabilizing the ABI.

Doug Gregor and Ben Cohen recently discussed many of these features on a two-part episode of the Swift Unwrapped podcast. Check out the podcasts here: Part 1 and Part 2

The most code-affecting (by elimination, in the case of Equatable & Hashable!) bits are the progress on the generics front:

Swift 4.1 adds more generics features to the language, furthering the goals set out in the Swift Generics Manifesto. The following generics-related proposals have been implemented in this release:

SE-0143 Conditional Conformance
SE-0157 Support recursive constraints on associated types
SE-0185 Synthesizing Equatable and Hashable conformance
SE-0187 Introduce Sequence.compactMap(_:)
SE-0188 Make Standard Library Index Types Hashable
SE-0191 Eliminate IndexDistance from Collection

For more information about progress made with conditional conformance in Swift 4.1, check out this blog post

Do indeed check out that blog post,

Conditional Conformance in the Standard Library

The Swift 4.1 compiler brings the next phase of improvements from the roadmap for generics: conditional conformances.

This post will look at how this much-anticipated feature has been adopted in Swift’s standard library, and how it affects you and your code…

TL;DR: Things like Optionals and Arrays and Dictionaries will now be Equatable if their contents are, the way things should work!

More than TL;DR: Swift 4.1 conditional conformance is 💖AMAZING💖  and Conditional Conformance

Also, if you’d like more mapping smarts in JSONDecoder, there’s help with that:

JSONEncoder: Key strategies

The strategy enum allows developers to pick from common actions of converting to and from `snake_case` to the Swift-standard `camelCase`. The implementation is intentionally simple, because we want to make the rules predictable…

More discussion in Swift 4.1 improves Codable with keyDecodingStrategy

And the common nil-stripping application of flatMap is deprecated: Replacing flatMap With compactMap

If you‘re trying to hit a binary size target, this’ll help: Code Size Optimization Mode in Swift 4.1

That’s about it for things we’ve noticed of interest, but there’s another comprehensive roundup over at Chez Wenderlich in What’s New in Swift 4.1? — anything we missed here is no doubt in there!

UPDATES:

compactMap for Swift < 4.1

Behind-the scenes improvements in Swift 4.1

Forcing Compiler Errors in Swift

How to use conditional conformance in Swift

What’s new in Swift 4.1? and playground

Ole Begemann’s Swift 4.1

What’s new in Swift? diffs any versions

Understanding protocol associated types and their constraints: “Swift 4.1 introduced the ability to make associated type constraints recursive: an associated type can be constrained so that it must also be of the same protocol…”

Conditional Coding with conditional conformance

Nine Releases Make An Xcode

All these new APIs are very well and all, but now let’s get to the really exciting stuff from WWDC:

What’s New in Xcode 9

  • All new editor. Fast, structure-based editor that lets you intelligently highlight and navigate your code. Includes great Markdown support.
  • Refactoring. Refactoring built right into the editing experience and works across Swift, Objective-C, Interface Builder, and many other file types.
  • Super-fast search. The Find navigator returns results instantly.
  • Debugging. Wirelessly debug iOS and tvOS devices over the network, new debuggers for Metal, and more features throughout Xcode.
  • Source Control. All new source control navigator and integrated support for GitHub accounts for quickly browsing repositories and pushing your repositories to the cloud.
  • Xcode Server built-in. Continuous integration bots can be run on any Mac with Xcode 9, no need to install macOS Server.
  • New Playground templates. Includes iOS templates designed to run well in both Xcode and Swift Playgrounds in iPad.
  • New Build System. An opt-in preview of Xcode’s new build system provides improved reliability and performance.

That is … a remarkable array of improvements. And those are just the highlights! Seriously, go Read The Whole Thing™. Most are runtime and debugging improvements, we’ll just pick out to highlight further here the changes in asset catalogs, since there’s some new resource stuff here you’ll want to be aware of to be iOS 11 savvy:

Asset Catalogs

  • Named colors support.
  • Added wide gamut app icons.
  • Added a larger iOS marketing to the App Icon set.
  • Added option to preserve image vector data for matching Dynamic Type scaling.
  • Added support for HEIF images.

The biggest one there is, as explained here,

Preserve Vector Data

There’s a new checkbox in the Asset Catalog Attributes Inspector called “Preserve Vector Data.” Checking this box will ensure that Xcode includes a copy of the PDF vector data in the compiled binary. At runtime, iOS can automatically upscale or downscale the vector data to output an image in your app whether you’re using the image in code or in a Storyboard scene. Remember: When using PDF vector data, set the “Scales” value to “Single Scale” in the Attribute Inspector to ensure the proper loading the PDF vector data to populate image.

This change also works in conjunction with the new Tab Bar icon HUD that Apple implemented as an accessibility feature in iOS 11. If you enable “Preserve Vector Data” this feature comes to your apps with no additional work. By enabling this feature, iOS 11 can also automatically scale images regardless of whether you’re increasing a UIImageView’s bounds, or using Size Classes to change an UIImageView size…

Screenshot samples at The Unexpected Joy of Vector Images in iOS 11.

And apparently Apple is bowing to popular pressure and making Xcode all but dependent on Github, see Xcode GitHub Integration and The Marriage of Github and Xcode 9. We’d mutter something curmudgeonly about why don’t you go full fanboi and replace the documentation with hotlinks to Stack Overflow too, but we’re worried they might take that idea seriously…

Community support we do find quite appealing though, is how enthusiastically the new stuff is being open sourced:

Apple open sources key file-level transformation Xcode components

This afternoon at WWDC we announced a new refactoring feature in Xcode 9 that supports Swift, C, Objective-C, and C++. We also announced we will be open sourcing the key parts of the engine that support file-level transformations, as well as the compiler pieces for the new index-while-building feature in Xcode…

And if that bit about “new build system” struck terror into your massively scripted heart, fear not, it appears to be pretty much a behind the scenes change all around:

New Xcode Build System and BuildSettingExtractor

The new system is written in Swift and promises to be a significant advance in a number of areas including performance and dependency management. The new system is built on top of the open source llbuild project and lays the foundation for integrating the Xcode build system with the Swift Package Manager

It appears that everything about defining build settings remains unchanged. Moving between the old and new build systems did not cause any build setting changes or recommended changes. The mechanisms for generating that giant bucket of key-value pairs known as build settings seem to be just the same as before.

This is great news. As developers, we don’t need to learn a new complex system for defining build settings. We get to enjoy the benefits of a new, faster, modern build system with our existing build settings left intact…

(And if you haven’t moved to .xcconfig files yet, or if you do them by hand, seriously do go check out BuildSettingExtractor. So handy, we even contributed to it — and that’s as high praise as it gets, around these parts!)

That’s enough for a TL;DR to get you salivating for the new stuff — but if you missed our link to New stuff from WWDC 2017 last time, go check it out now; more details on Xcode changes there … and everything else as well. Veritably encyclopedic, that reference!

OK, one last note that isn’t Xcode 9 specific but you’ll want to refer to it anyways: iOS Simulator Power Ups. Something for everyone there!

UPDATES:

Hands-on XCUITest Features with Xcode 9

Customizing the file header comment and other text macros in Xcode 9

iOS Simulator on steroids: Tips & Tricks

Little Xcode Beta Surprises 🎁: Core Graphics Codable Conformance

Measuring Swift compile times in Xcode 9gist example — Two Useful Environment Vars

Awesome native Xcode extensions

Secret variables in Xcode AND your CI for fun and profit ?

Xcode 9 Vector Images

Managing different environments in your Swift project with ease

Conditionally embed your dynamic frameworks

Everything You Need to Know About Ruby for iOS Development

Optimizing-Swift-Build-Times: “Collection of advice on optimizing compile times of Swift projects.”

Swift compilation time debugging options and their outputs

Let’s Optimize the Work with Terminal for Xcode Developers

Easy XIB and Storyboard Localization

Some useful URL schemes in Xcode 9

IBLinter: “A linter tool for Interface Builder”

AutoLayoutLint: “Provides automated test to detect runtime conflicts of constraints.”

More Interface Builder Tips And Tricks

XcodeGen: “Command line tool that generates your Xcode project from a spec file and your folder structure”

Edit Breakpoints in Xcode

XcodeWay: “An Xcode Source Editor Extension that helps navigating to many places easier.”

Highlight Warnings in Xcode

Care and Feeding of Xcode Configurations

How to find and fix slow drawing using Instruments

How to find and fix memory leaks using Instruments

How to find and fix slow code using Instruments

Xcode Releases

Wrestling with a Monstrous Xcode Project

Compiler Optimizations, Compiling Optimally, and Whole Modules

Periphery “analyzes projects written in the Swift programming language to identify unused code.”

Tip: add “time” to your build scripts

Xcode Project Linter (xcprojectlint): “A security blanket for Xcode project files”

Getting (nearly) rid of Xcodeproject – A (not so) short Introduction to Xcodegen

Periphery: Eliminate Unused Swift Code

Running Xcode and Simulator in fullscreen

Roundup: Xcode Tips

Aaaaand to celebrate today’s release of the iPhone OS 3.1 SDK with the latest Xcode versions for Leopard and Snow Leopard, let’s make a list of useful Xcode tips and resources from around the web, shall we?

Oldies but goodies:

Stack Overflow’s Xcode Tips And Tricks

Mobile Orchard’s 14 Essential Xcode Tips, Tricks and Resources

Up-to-the minute stuff:

Static Code Analysis (Clang) and Xcode 3.2

Complete Xcode Keyboard Shortcut List

clang Source Annotations

Helper Goodies:

BuildCleaner

Accessorizer

Any others you find particularly useful, Dear Readers?

Tool: BuildCleaner

Here’s a handy little utility called BuildCleaner for, eponymously enough, cleaning up all those Xcode build folders that litter your drive:

I just wanted to let you know of a little utility app I’ve just posted, called BuildCleaner. As I explore example projects, open source frameworks, and test applications, I find that I usually have a lot of build folders cluttering my hard drive. When you combine that with backup services like Time Machine, Mozy, or DropBox, you can waste a lot of your bandwidth uploading build folders.

To help with this, I’ve created BuildCleaner. It’s a little menubar application that scans your hard drive every few minutes for build folders and deletes them if they haven’t been modified recently (you can change the cutoff interval in the settings window). You can also tell it to ignore the build folders of specific projects, such as the humongous project you’re following that takes ages to compile, but you only crack it open every couple of days…

Handy, indeed. And it’s been open sourced on github for your tweaking pleasure as well!

h/t: cocoa-dev!

Xcode predefined macros

Here’s a couple tips for finding what macros are defined/available in Xcode that showed up on xcode-users for the question

Hi, I’m looking for information on Xcode or the preprocessor that would indicate whether or not my code is being compiled for a non Mac GNU target or Mac OS X or iPhone OS…

You might have known this answer, how to print out a list of gcc predefined macros from the command line:

gcc -E -dM -x c /dev/null

But we’ll just bet you didn’t know how to extract them for a particular file in compilation context!

The easier way to do this (and get more precise, per-target-per-configuration results from Xcode) is to select a source file, Get Info, click the Build tab, add -dM to it, then Preprocess that source file.

You know, there’s been times when porting particularly convoluted befuddlements of allegedly cross-platform libraries that having known that tip would have saved us literally days of flailing around…

Tools: Accessorizer

This looks like it might be a handy tool for the Xcode programmer: Accessorizer!

Accessorizer saves you tons of time … Those minutes add up  to hours, days and weeks over the lifetime of a project.

Accessorizer selects the appropriate property specifiers based on ivar type – and can also generate explicit accessors (1.0) automagically …  but Accessorizerdoes much, much more …

Accessorizer will help provide you with the init, keypath, keyed-archiving, indexed accessors, accessors for unordered collections such as NSSet, copyWithZone, KVO, key-validation, singleton overrides, dealloc, setNilForKey, non-standard attribute persistence (Core Data), locking, headerdoc, convert method to selector, NSUndoManager methods and more.

Well, it does sound handy, doesn’t it now. Anyone out there tried it? Worth the price you figure?

h/t: iPhone Development Blog!

Tip: Debugging exceptions

Don’t you just hate it when you finally get your program linking, you run it, and instead of seeing your glorious code executing away you get something like this?

2008-11-13 21:12:25.866 Play MPE[1369:20b] * -[PMPELoginViewController loginSucceeded:]: unrecognized selector sent to instance 0x40d560

2008-11-13 21:12:25.867 Play MPE[1369:20b] * Terminating app due to uncaught exception

Most annoying, that. So what can you do to catch that kind of nonsense in the act? Or other runtime failures?

Well, the Breakpoints window in Xcode (Run > Show > Breakpoints) is your friend. Simply add these project or global breakpoints:

objc_exception_throw

+[NSException raise:format:]

_NSAutoreleaseNoPool

_objc_fatal

malloc_error_break

and then hey presto, the debugger comes up stopped on the source line, in this case

[self loginSucceeded:loginResultData];

Much easier to debug, that!

[EDIT: And here’s some others you might try as well:

NSInternalInconsistencyException

NSInvalidArgumentException

]

h/t: iphonesdk!

All about C99

Yep, we’re always on the cutting edge of the latest news and breaking developments here Under The Bridge, so today we’re going to talk about — wait for it — the C99 standard for the C programming language!

Um, you may understandably be thinking, how does ISO/IEC 9899:1999, published 1999-12-01, qualify as a breaking development now exactly?

Well, grasshopper, it’s a breaking development because it has recently come to public light on the xcode-users list that recent versions of Xcode have changed the default C language dialect to C99, apparently deciding that GCC 4.0’s C99 feature support can now be deemed complete. So that means that if you’re using Xcode to target Any New Device Currently Under NDA™, it would behoove you to clue into just what’s changed and different in this “new” version of C. And, conveniently, this fine fellow David Hoerl has put together a reading list for us:

It took a while but I finally did uncover a really good series of articles written by Randy Meyers for the C/C++ Users Journal several years ago. Posting these here in case you have been thinking of doing the same in the near future:

The New C: Introducing C99

The New C: It All Began with FORTRAN

The New C: Integers, Part 1

The New C: Integers, Part 2

The New C: Integers, Part 3

The New C: Declarations & Initializations

The New C: X Macros

The New C: Compound Literals

The New C: Why Variable Length Arrays

The New C: Variable Length Arrays, Part 2

The New C: Variable Length Arrays, Part 3

The New C: Variable Length Arrays, Part 4

The New C: bool, Advice to C and C++ Programmers

The New C: Inline Functions

Statements and Loops

Floating-Point Math

About // Comments

And if you’re not satisfied by all that, there is also available The New C Standard: An Economic and Cultural Commentary, a 1615-page book which annotates the entire standard, sentence by sentence. And it’s completely free, as Addison-Wesley backed out of publishing it once they got a look at it. Probably not a wholly indefensible decision on their part, as it’s not exactly what most people would consider a gripping page-turner, but it is remarkably exhaustive in its coverage.

h/t: xcode-users!

Under The Bridge Store now open!

[UPDATE: Amazon killed aStores in 2017.]

So we’ve created an Amazon store to guide the Gentle Reader to how they should go about building their iPhone programming library, as well as — hopefully! — support further building out our own.

It is, naturally, called the Under The Bridge Store. Take a look now!

The layout is, the front page “Coming Soon!” is things that we haven’t examined personally, but we figure probably will turn out worth buying. Whatever earnings this store produces will be applied directly to buying things on that page, and we’ll review them here, and then either move them to the other categories or delete them as we judge appropriate.

The other categories are all books that are, indeed, in our reference library right now, and we believe should be in any iPhone programmer’s library, divided by main focus into “Programming – iPhone”, “Programming – OS X”, and “Programming – General”. We may get around to specifically reviewing those at some point in the future — although hopefully we’ll be focusing on exciting new goodies instead of the old stalwarts — but they all have at least a few Amazon reader reviews so you can go by those in the meantime.

Browse, enjoy, and buy!