Making Cocoa the Outermost Layer

Chris Eidhof of objc.io put some experimental code on GitHub where quite a few Cocoa view components are contained by classes he owns himself. The AppDelegate is super instructive: Your Cocoa app needs an NSApplicationDelegate
. But it doesn’t have to do anything except route events to the proper collaborators. Still it’s the first object we usually put logic in only to (hopefully) refactor it out later.
Encapsulate a Process in a Single Line Using Bind and Good OO Design
Watch Saul Mora’s AltConf presentation “Object-Oriented Functional Programming: The Best of Both Worlds!” to learn more about real world use of bind
and other functional concepts in object-oriented programming. His examples are really good.
Segues: How to Use Them While Saving Lines of Code
In “What’s New in Storyboards” of WWDC 2015, we’re presented with implementations of unwind segues. Now I’ve stated part of my concerns with segues and app architecture already. The sample code was very straight to the point:
Separate Read Model from Write Model to Support Complex Forms
One thing that repeatedly messes up the conceptual purity of a view model is figuring out which entity should be mutated upon user interaction. Part of this purity stems from the fact that a view model is best served as view data to stress that it doesn’t contain much (business) logic. Making the data mutable introduces a lot of problems figuring out what that view model really is.
iOS View Architectures and VIPER Explained
There’s an excellent overview of MVC, MVP, MVVM, and VIPER in iOS with sample codes by Bohdan Orlov of Badoo I recommend you read.
There are two main takeaways:
- One of the commenters nailed it: any MV* variant focuses on architecting view components. Only VIPER takes the application as a whole into account. MVC by itself is an architectural pattern, but not an approach to app architecture in itself.
- A
UIViewController
belongs into the user interface layer and is, in fact, a composite view itself. That’s confusing at first because of the name. This insight will liberate you from thinking that a view controller is sufficient to glue data to UIKit components. There’s room for a whole application between these two.
The VIPER example is exceptionally good. It takes VIPER’s heritage of Clean Architecture and Hexagonal into account and defines the Interactor through an output port. In that way Bohdan’s sample code is more east-oriented and cleaner than what you’d usually find on the topic:
protocol GreetingProvider {
func provideGreetingData()
}
protocol GreetingOutput: class {
func receiveGreetingData(greetingData: GreetingData)
}
class GreetingInteractor : GreetingProvider {
weak var output: GreetingOutput!
func provideGreetingData() {
let person = Person(firstName: "David", lastName: "Blaine") // usually comes from data access layer
let subject = person.firstName + " " + person.lastName
let greeting = GreetingData(greeting: "Hello", subject: subject)
self.output.receiveGreetingData(greeting)
}
}
Usually, you’d model provideGreetingData()
as a function that returns the data to the caller. This will cause trouble in async processes of course.
You see in the full example that the amount of types seem to explode. Don’t be afraid of that as long as you can assign each type a specific responsibility. Then it won’t turn into the mess everyone seems to be afraid of.
Having used VIPER in apps myself, I see a problem with the names, though. XYZInteractor
and XYZPresenter
aren’t much better than XYZController
in terms of expressiveness. On top of that, a concrete Presenter is always modelled to act as event handler, too. Don’t let this fool you into thinking you absolutely have to do this yourself – there’s always room to separate writing from reading operations, or event handling from view population.
Make Money Outside the Mac App Store

Today I’m proud to announce the release of my e-book Make Money Outside the Mac App Store!
Get it for $25 $19 until Dec 24th from my store!
Shaving off VAT and then again 30% for Apple for every purchase of your app in the Mac App Store can be madness: the only real benefit is that people know how to operate the store. But if you’re just starting to run your business, discoverability is hardly a feature.
Instead of drowning in the warehouse that the app store is, put your software in your own store. You have to build an audience anyway to get started. So stay in touch with them. Know your customers. And stop giving away 30% for a promise that doesn’t hold.
- Save days of research and implement the techniques today
- Copy & paste Swift 2.0 code to integrate into your app in <1 hour
- Utilize in-app purchase of licenses for a higher conversion instantly
- 2 fully functional sample applications, including a time-based trial app
- Secure license code generation and verification included
Take a look at the details page for more info.
This book will save you hours of research and days of fiddling with SDKs. It shows you how to set up products for sale on FastSpring including automatic license code generation and then guides you through the process of adding license verification to your app.
Don’t need all the explanations? Just follow the setup steps and copy the code into your project and you’re ready to roll in half an hour!
I’m not affiliated with FastSpring. I just think their service is awesome.
Here’s what FastSpring’s CTO Mike Smith has to say about the book:
We appreciate Christian’s efforts in creating a guide that enables Mac developers to sell applications through FastSpring’s award-winning e-commerce platform. He has provided detailed instructions to help developers configure key elements of their online sales process. The spirit of community captured in his book reflects FastSpring’s mission to connect people globally in the digital economy.
I truly believe in the spirit of community and I believe you can make it as a developer without the App Store. This book is here to empower you so you don’t have to figure out all the scary details.
So many other indies rely on FastSpring, too, including:
- Smile Software (TextExpander, PDFpen)
- Realmac Software (Clear, RapidWeaver)
- Tyler Hall (VirtualHostX)
- Ironic Software (Yep, Leap)
- Bohemian Coding (Sketch)
- toketaWare (iThoughtsX)
- well, and me, obviously :)
Get to know their stories from this book. Be inspired and take the leap.
Because I think it’s so worth your time as a Mac developer, get it for 25% off until Christmas when you buy from my store.
Yelp’s Modular UITableViews
Yelp reuses a setup of modular table views across their huge app. A simple timeline entry can be composed of 5 cells, each with its own model representation. These cells are used to create various component setups. What I find most interesting is the combination of registering cells for reuse identifiers in one place and using reuseIdentifierForCellAtIndexPath
in another.
Extract UITableView Contents and Configuration Into Helpers
In a top secret project I am working on, I think I found a consistent way to create UITableViewController
s in a reusable fashion without making a mess with massive view controllers. The key ingredient is, as always, delegation from the view controller and thus composing larger components:
Configuration Objects: Delegate Initialization to a Parameter
The Builder design pattern is often overlooked, I find. Apart from plain builders, in Ruby I found that some us it like a configurator. You can use a configuration object in Swift in the for of block parameters, for example: This would make the internals of ComplexThing
configuratable through the block. Instead of messing around with an instance of a ComplexThing
, you can do atuff with the configurator which determines how the instance will look.
Parameter Objects Simplify Your API Versions
I watched an AltConf about API design the other day. I cannot seem to find which talk it was, though. Anyware, the presenter talked about using parameter objects when the parameter list grows too long or is open for change in future versions. Parameter objects can change internally and evolve with the API. You can add or remove attributes, for example, while the API calls of old client code don’t have to change: they still pass the same type in. That makes framework updates a bit less painful because method signatures stay the same.
Presenter and MVVM for UITableViews?
When I wrote about MVVM with a “control” which really was a presenter, the view in question displayed some kind of data. Any sufficiently complex view would do, but the example focused on a view controller which consisted of a single composite view. UITableViewController
s are a different kind of beast, though.
How to Handle Errors When You’re Not Interested in the Details
I read a post by Erica Sadun about making try?
more useful. This new variant of the keyword transforms thrown errors into nil
. That can be convenient, but it doesn’t help handle the errors. Erica proposes a wrapper which logs errors. I like that idea and take it a step further.
Switching iOS App Login Methods by Creating Your Own Simple Login Module

I really like the power of enums in Swift, so I was naturally inclined to see what the presentation “Simplifying Login with Swift Enums” by David East had to offer. Here’s the setting: you’re going to offer multiple ways to authenticate users with your app. How do you model this?
Tips to Conquer Massive View Controllers
View Controllers should only be responsible for view lifecycle events, Marcus Zarra reminds us. That means they should populate views with data, and show and hide them – stuff like that. View controllers should not do the work of views.
While I like his overall advice, it contains a few problematic points:
- Put Core Data out of the view controller. His solution to provide a single data source tied to a
NSManagedObjectContext
will not scale well as I’ve experienced. – Still, don’t tie it to the view controllers. That makes matters worse. - His definition of “business logic” is odd. Business logic is not reducible to I/O code. It’s not just about fetching data from a device and doing network requests – except when your app is a very, very simplistic display for data with CRUD operations. Business logic can exceed data-centric rules and entail a real domain with complex behavior without much imagination.
- Views should be responsible for displaying data, agreed. Since validation problems will be presented to the user, validation error messages will be part of that data, too. But views should not validate. Validation rule objects (WWDC’14 talk) should be the strategies that do validation.
If we create an object to sit between the view and the view controller then we are creating unnecessary additional objects.
Where do presenters sit? Between view and and view controller – but they make it easier to read and extend the code. They’re hardly unnecessary.
I strongly believe that it’s impossible to give advice about how to code and architect something if the problem domain isn’t part of the example. Because everything depends on the problem space in the end.
Remember to take every advice with a grain of salt. Collect things like Marcus’ tips to obtain new tools, but don’t take the tool for the solution of modelling a program to solve real problems.
Ruby 2.3 Will Have Optional Chaining
Swift, C#, and Groovy had it – now Ruby 2.3 will get it, too: a “safe navigation operator”, or what we call “optional chaining”.
Instead of:
if u && u.profile && u.profile.thumbnails && u.profiles.thumbnails.large
You can now write (with the beta):
if u&.profile&.thumbnails&.large
They didn’t use the ?
because Ruby method names usually have a postfix question mark when they return a boolean; also, they will have a postfix bang when they mutate the receiver. This would’ve led to confusion.
Since Swift came out, I haven’t used Ruby a lot, really. I still use it for all my scripting needs, but coding real applications? Rarely. I really like strong typed languages for that: leaning onto the compiler for refactorings and such.
See the Ruby enhancement issue if you’re curious.
Jiggle GCD Queues to Find Problems
To debug my threading issues and help bring forth future problems, I have created a simmple object that slows the current queue down:
let IsRunningTests = NSClassFromString("XCTestCase") != nil
struct QueueJigglePoint {
/// Randomly interfere with the thread.
static func jiggle() {
guard !IsRunningTests else { return }
#if DEBUG
usleep(2*1000000) // 2 seconds
#endif
}
}
I got this idea from Brett Schuchert on pages 188–90 of Uncle Bob’s Clean Code. A Handbook of Agile Software Craftsmanship. There, interference with traditional threading should randomly sleep, yield, or fall through. Enqueued blocks are a lot less volatile, so I only came up with sleeping.
Randomizing the sleep interval is up next. But a fixed number of 2–10 seconds helps find UI-blocking code already.
Just throw in a QueueJigglePoint.jiggle()
in NSManagedObjectContext.performBlock
executions, when dispatching async to the background, or when reading files, for example.
Modeling: From Structured Data Representation to Problem Domain

Recently, I was discussing adding a feature to an application which is about event creation and booking. The project manager has a strong database background and works on the schema himself. The schema is also his go-to tool to express changes in the features. But thinking about the real Domain in terms of objects revealed much, much more.
Swift OS X Programming for Absolute Beginners Review

Recently on Google+, someone recommended Wallace Wang’s Swift OS X Programming for Absolute Beginners. Well, I’m not a beginner anymore, but the book sounded fun, so I gave it a spin. And I’m quite impressed. That’s why you read the review here. In short, Swift OS X Programming for Absolute Beginners (or SOXPAB as I would like to call it to save myself from typing that much) is the best programming book to teach the reader about user interface programming. I can’t honestly judge how well this textbook will actually work for non-programmers. But that’s because I can’t fathom learning to code from a book anyway. If you know programming, or the Cocoa APIs already, this should work for you.
Core Data Calls Them Contexts for a Reason
It seems the Unit of Work I envisioned is not the one I need. It seems Core Data calls NSManagedObjectContext
a “context” for a reason. It doesn’t suffice to set one up and pass it to every data store. At least not if you perform changes on background queues and with nested contexts.
Ideas to Solve Background Fetching and Saving Race Conditions with Core Data
I ran into problems with my Core Data Unit of Work/Transaction implementation the other day. I was not exercising good NSManagedObjectContext
hygiene and end up with conflicts from time to time. Race conditions. Hate ‘em. The problem is that the parent–child setup of Core Data managed object contexts seems to work just fine for so-called “scratch pad” contexts: create a new child context, perform changes on in, then discard, or save to pass changes to the parent context.
Productive Writer’s Bundle Sale

This year, the team of Texts, Brett and I teamed up to bring you the best minimal writing product bundle for the Mac. It’s designed to get you through NaNoWriMo: the accompanying guide tells you how to make the habit of writing stick and how to get most out of the apps.
The lineup of apps:
- Texts for focused writing (even on Windows PCs!)
- Marked for previewing and reviewing
- Word Counter to increase your productivity
- BONUS: iThoughts X (coupon for 30% off) to plan the plot with Mind Maps
- BONUS: Minimal Writing on the Mac guide
I use these apps myself to write, so creating this bundle was a no-brainer and a very exciting experience – oh was I busy! – but more on that later.
The Productive Writer’s Bundle is a sexy deal at more than 50% off, for $25 instead of $60 – for every author, be it novelist or non-fiction technical writer.
Grab it now. And tell your friends.
What It Means to Domain-Drive Your Design
I’m currently reading Object thinking by David West to get more general input on object-oriented programming. So far, it seems that most of the cool stuff I discovered for my coding practice in the past years is actually ages old. (Of course this is my interpretation, based on my current knowledge, re-producing and re-discovering expected results in new words.)
Word Counter Now with File Monitoring

The Word Counter received a huge update this week. It now allows you to monitor files. That means you can create a record of your project progress. The usual words-per-hour meter will tell you how well you perform, while the file monitor can tell you how far you’ve come.

I’m excited to finally release this update. I think it’ll help motivate a lot of people to make progress and marvel at their current achievements.
Up next is a graphical representation of all this, because visualizing helps to see progress, obviously.
If you have trouble downloading the update, please get a fresh download from the website. This will probably affect a lot of people. I’m very sorry for the inconvenience!
Don’t Build on El Capitan Without Checking App Transport Security
I got burned this week. Pretty bad. I shipped a small bugfix release for my Mac app Word Counter a couple of days ago to prepare for the “big one” coming this week. Naturally, I built that version on my El Capitan dev machine. I pushed the update to my server. Updates using Sparkle worked. – But now users of that version cannot ever update to the next version. Because I haven’t thought about ATS.
NSOpenPanel’s and NSSavePanel’s Block-Based API is Superior
I got angry at NSOpenPanel
the other day for visually blocking NSAlert
s, and for staying in the way when the debugger hits a breakpoint. Silly me, I used ye olde runModal
. When you use the block-based API of NSSavePanel
or its decendant NSOpenPanel
, all of a sudden they will display on top, but only per application. Also, alerts seem to have a higher display level in these cases.
Small Helper Objects Take You Far

Integrating new functionality is fun. But revisiting 18-months old code isn’t. Back then I created a protocol InvokesWindows
to define methods like -showPreferencesWindow
which I imported in the menu bar controller to show the preferences when the user selects a pop-up menu item. But I didn’t actually delegate to any instance of InvokesWindows
. I used NSApp
. (Insert facepalm here.)
How I Solve the Unexpected Error Handling User Experience Problem

For the upcoming Word Counter upgrade, I developed a new feature module in isolation. The outcome is very interesting, as I am including it as a Swift module, that is as a real framework, into the existing app. I need some more time to write about the resulting architecture, but I found the module boundary to be really helpful. Today, though, I want to share my ErrorHandling
code.
Make Custom Debug Build Configurations Play Nicely With CocoaPods
To test the Word Counter during development, I have long used a special build target. But that doesn’t scale well if all I want is change a preprocessor macro to switch from file-based to in memory storage, for example. I’ve never played around with build configurations in Xcode. They work well with Schemes, though, and setting up a build configuration and a scheme is much less overhead than maintaining a custom target.
Optional Protocol Methods in Swift using Closures and No Protocol, Actually
So you miss declaring optional methods in Swift protocols? Joe Conway
got you covered: “optional methods can be implemented by providing a default implementation in an extension.” But there’s an even better way, in my opinion: ditch the notion of optional methods and use blocks instead.
Achieve More with a Variety of Value Objects in Swift

From the department of Domain-Driven Design code patterns, I today present to you: well-named value objects! You can go a lot farther than you have previously imagined with value objects in Swift. Now that Swift is more than a year old, most of us have seen the use of struct
and heard how useful passing objects by value is.
Decouple UI from Model with View Models and Controls
Lammert Westerhoff compared MVVM to Presentation Controls recently. Since nobody likes massive view controllers, I had a look, too, and found a few interesting things. To write a real app with his tips in mind, we’re going to need a bit more, though, and refactor things a bit.
How to Move Bootstrapping Code Out of AppDelegate

The test project I work on to develop a component of the Word Counter faster sets up a lot of service objects during launch. I shaved off 60 lines of AppDelegate
by introducing bootstrapping as a thing to my code. This way you can prepare a list of Bootstrapping
components and iterate over them to set up one after another.
Transactions and Rolling Back Changes in Core Data with UnitOfWork
The Unit of Work pattern is a code equivalent to database transactions: when it completes, changes are persisted; when something fails, changes are rolled back. That’s handy to perform a set of changes and have them saved. Sooner or later during app development using Core Data, you may ask: when should I save? When is the best point in time?
Leave a Rating for Move! app on MacUpdate
Move!, my personal favorite productivity and health enhancement app (and, apparently, my own creation), is now available on MacUpdate. Check it out for free if you haven’t already.
Please leave a quick rating on MacUpdate so other people know how good you feel, now that you take regular breaks from work.
If you feel super-awesome today, feel free to leave a short review, too.
Your support helps me continue my work. Every star counts! ⭐️⭐️⭐️⭐️⭐️
Thank you!

Put Usage of a CoreDataFetchRequest out of Your Code and Into … Where Exactly?
I created a generic CoreDataFetchRequest a while ago and love it. It casts the results to the expected values or throws an error if something went wrong, which it shouldn’t ever, logically – but the Core Data API currently returns AnyObject
everywhere, so I have to deal with that.
Revisiting the Core Data + Domain Model Architecture
It happens that just yesterday I read about architecture smells in code. Among the examples was “subclasses don’t redefine methods”. In my post about Core Data and expressive domains earlier this week, I did just that: create a Egg
subclass of CoreDataEgg
to inherit CoreDataEgg
’s behavior. That’s not what abstraction to superclasses is meant to do.
Expressive Domain Model, Core Data, and You
I’ve written a whole book on the topic of architecting a Mac app using Core Data. Today I found an approach which doesn’t add lots of overhead and which also doesn’t clutter everything everywhere. It’s pretty simple and involves Swift.
Chaining Events, Take One
In an execellent book on Domain-Driven Design that I’m reading in my spare time, they make a lot of use of domain events. I’ve written about a strongly typed publish–subscribe infrastructure in March already to get you started. Some of the book samples include what seems to be ad-hoc event subscribers. I try to port that to Swift.
How I Now Deal with Collapsible Split View Controllers on the iPhone 6

So UISplitViewController
is the new default for iOS apps. Most iPhones have compact-sized size classes. iPads have regular sized ones. The iPhone 6(s) Plus mixes both. Only horizontally regular-sized environments show both the master and the detail scene (or primary and secondary view controller).
Universal Deep Linking on iOS: Design Each Scene to Be Remarkable
Deep linking in iOS is all the hype. It’s interoperability opens up the platform both for developers and users. But it brings new transitions to the platform and with them new responsibilities to design your application.
Move! – Work Break Timer Now Ready for El Capitan

The Apple Watch is all the hype since it gently reminds you to stand up and move regularly. That’s a very good thing. A gentle reminder won’t cut it for me. That’s why I created a solution which jumps right into my face.
Look at the project page of Move!.
It features responsive timers: when you don’t touch your input devices, the clock will not start to tick. Only when you sit down and work will the timer start and make you stand up soon.
Move! is now ready for El Capitan. The upcoming OS X update can come!
Swift Protocol Extensions as Mixins – And How Do You Test That?
I found a very useful distinction by Matthijs Hollemans to grasp what protocol extensions in Swift 2 can be: instead of interfaces, they are traits or even mixins. At the same time, I want to raise awareness for misuse: just because behavior is mixed-in doesn’t mean it’s additional behavior. The code may live in another file, but its functionality can still clutter your objects.
Testing Shorthand: Use a Subclass of the Real Object Under Test

I just found a shortcut to use Dependency Injection less during tests. In “Unit Testing in Swift 2.0”, Jorge Ortiz adapts solid testing principles to Swift. If you don’t have a strong testing background, make sure to watch his talk for key insights into the How using Swift!
Make Money with Mac Apps Outside the MAS: E-Book Prerelease, Need Feedback
I have written a book about releasing apps outside the Mac App Store. It comes with two fully working sample applications to cover checkout from within the app, licensing, and locking the app after a trial period.
It’s called:
Make Money Outside the Mac App Store: How to Sell Your Mac App with FastSpring, Secure It With License Codes Against Piracy, and Offer Time-Based Trial Downloads.
I’d love to have feedback on this.
If you want to help out, just shoot me a line at: hi@christiantietze.de
Thanks!
P.S.: The secret Leanpub page is here.
Using Guard in Unit Tests
I have just discovered how cool the new guard
statement is to keep unit tests lean and shallow – avoiding if-let nesting, that is. Update 2021-05-11: Modern XCTUnwrap
is even better. Consider this test case: There are two optionals I have to deal with. That’s why I throw in assertions to cover problems. I don’t want to assert anything new here, though: the test helper soleFile()
is valdiated in another test case already. But I need some kind of failure in case the Core Data test case goes nuts.
Save Yourself Casting Headaches with a Generic Fetch Request Object
Swift 2 brings a lot of Cocoa API changes. For one, Core Data’s NSManagedObject
’s executeFetchRequest(_:)
can throw, returns a non-optional on success, but still returns [AnyObject]
. While refactoring existing code to use do-try-catch, I found the optional casting to [MyEntity]
cumbersome.
How to Change the Detail of a UISplitViewController in the Background
A UISplitViewController
has a master and a detail view controller. When the selected item is deleted and the detail is visible, you can perform a segue. If the detail is not visible, performing a segue to change the detail will present it. I didn’t want that. There are two cases where you will want to change the detail although it’s not visible:
Dismissing a Modally Presented Scene on Both iPad and iPhones Using Unwind Segues
UISplitViewController
is the way to go when you want to make your iOS app universal without much hassle and can model the scenes in terms of master/detail. While getting Calendar Paste ready for the upcoming iOS 9 release, I discovered that using UISplitViewController
across devices is one thing, while Storyboard segues are another.
Weird EXC_BAD_ACCESS in Swift 1.2 Was Due to A Compiler Bug
I banged my head against Xcode’s wall (which is my computer screen) today, trying to find the source of an EXC_BAD_ACCESS code=2
termination. Turns out it’s the Swift 1.2 compiler which doesn’t catch a problem here. The signature of the block causing trouble with the version shown above:
How to Create Flexible Components with Two Levels of Service Objects
Again I was reminded about the value of service objects to encapsulate sequences in two places: the Domain, where business rules are kept, and in client code, where database management and transactions play a role. This distinction helps create clean code and deliver flexible components. I am building a feature for the Word Counter in a separate “library” project until everything runs smoothly. Then I’ll integrate the code into the main application. Since I consider this to be some kind of library, I thought I wouldn’t need many service objects, but I was wrong.
What is CLEAN Code?
Writing clean code makes your life better in the long term, and I find it’s more fun initially. According to Bernstein, CLEAN is an acronym:
- Cohesive
- Loosely Coupled
- Encapsulated
- Assertive
- Non-Redundant
His book “Beyond Legacy Code. Nine Practices to Extend the Life (and Value) of Your Software” seems to be a good read. Not through, yet.1
-
Affiliate link; I get a small kickback from the vendor if you buy from my link but it won’t cost you anything. ↩
Move! – Work Break Timer Release

During summer, I have created a work break timer called Move! which really works. It gets in your way, it cannot be postponed. I created it to make me get up and stretch and do something else for a couple of minutes every half hour.
Sascha and I plan to add exercise instructions later. Right now, we’re happy to have a tool which forces us to get up every now and then and get healthy. (Backed by research, mind you!)
It will get on your nerves. Continue to take breaks when it tells you to.
You’ll hate it.
You’ll yell at it.
But it will make you feel better in the afternoon.
Do yourself a favor and try to do some diagonal stretches or a healthy 1-minute routine.
Download Move! on its dedicated page now and experience it for yourself.
Where Instead of Using Functional Bind, I Create an Expressive Model

The other day, I wrote a post about bind()
and the >>=
operator and how it can help chain function calls together. The example was a bit too contrived and making it fit the requirements left us with really bad code. I came up with an even better implementation: use plain Swift objects and express your intent carefully.
Create UML Diagrams Quickly with Draw.io

It happens quite a lot that I want to create a small UML diagram. Mostly for this website, but often for books, too. All the Java-based Mac applications get on my nerves quickly, though. That’s when I found draw.io the other day. It’s simple, lightweight, and works from within your browser with various storage options.
Cut-Out Animation of a Table View Cell Into the Next Scene
I haven’t dabbled with animation a lot. So I was pretty surprised that there’s a method on UIView
called snapshotViewAfterScreenUpdate
which creates a static duplicate which you can use for animations easily.
I found this in a AltConf talk by Marin Todorov called “Power Up Your Animations!”. There, he does … well, I don’t know what it’s called, or else I would’ve picked a better title. See for yourself.
Here’s a crappy screen capture of the animation in his talk in action:

His code is on GitHub, where you can check out how the TableCellAnimatior
works. I think this is a very amazing, yet subtle animation. I find it unbelievable how easy it is to implement.
It seems I have no reason to fear animation in the future.
From East-Oriented Programming to Functional Bind

East-Oriented programming can, for example, be implemented through delegates or callback blocks. “East” is all about Tell, Don’t Ask: don’t query for values; instead, pass a handler around so the flow of information doesn’t return to your current scope.
How to Write Pragmatic, Testable Singletons in Swift
Singletons have their use. I use two Singletons regularly in my projects: a DomainPublisher
and a ServiceLocator
. The latter is a registry of service objects which is global so the service objects don’t have to be. For practical use, most Singletons are overcomplicated or overly restrictive. Here’s how I suggest you implement Singletons in your apps:
Refactoring Legacy Code: Replace Free Function in Tests, Even Swift’s Own Functions

Refactoring Legacy Code is hard. There are a few safe refactorings you can do with caution. But most chirurgical cuts require you to put the code in a test harness first to guard against regression. With C and Swift, you can create free functions as part of your app. To verify your objects use that function, you need to find a way to insert a test double.
Support the Word Counter With a Review

I’m working hard on the Word Counter. By October, I’m going to finish a really big feature: file and folder monitoring. It’s a pretty tough ride till then to get it done.
Since the Word Counter is not on the Mac App Store, please show your support and leave a ★★★★★ rating on MacUpdate.
You don’t have to write a full review in order to leave a rating. Just click the five stars at the very top of the page – but a review is much appreciated, of course!
As always: if you experience any hiccups on Yosemite or El Capitan, please tell me so I can fix the bugs.
Library for Providing Static UITableView Contents in Swift
I discovered a Swift library called Static the other day. It helps set up and fill UITableView
s with static content – that is, it doesn’t permit deletion or rearrangement of new rows into the table. I think the following example to configure sections with rows reads really nice:
“Exploring Mac App Development” Updated for Swift 2.0 + Coupon to Save 50%

It’s a good time to update my book for Swift 2: guard clauses improve readability, and do-try-catch error handling shows problem points. Protocol extensions are huge, but I had no use for them in the sample code, yet. The update is live now. If you haven’t bought the book in the past, grab it until August 1st to save more than 50%: use the coupon Swift2Yay. The coupon is good for 10 copies, so be quick.
How Coursera Uses VIPER to Architect Transitions Between App Features

Oy vey, now there’s a ton of AltConf 2015 talks online, too! So much to digest! In “250 Days Shipping With Swift and VIPER” by Brice Pollock, he shows how the folks at Coursera do some clever things with the VIPER iOS app architecture: they use a Router
which handles internal URLs.
Refactoring a View Controller for Clean Information Flow

There’s a WWDC 2014 talk called “Advanced iOS Application Architecture and Patterns”. In the first 30 minutes, you can learn a lot about designing information flow in your app. Sticking to Andy Matuschak’s example, a view controller is usually the place to put all behavior. (Hint: this is a bad idea.)
Using Blocks to Realize the Strategy Pattern
There’s this saying that the Strategy pattern can be realized in Swift using blocks. Without blocks, a Strategy object implements usually one required method of an interface (or protocol) to encapsulate a variation of behavior. This behavior can be switched at runtime. It’s like a plug-in.
Clean Coding is a Programming Misnomer for a Software Engineering Principle

I found a cute info-graphic on how to become an iOS developer by John Kim. This study guide contains a passage with a very interesting distinction between programming and engineering. Thanks to it, I found out a detail about what it means to write “clean code.”
Citing from the graphic:
Programming is like building the bridge. You need to know how to use the tools to get your end result. In this way, you need to know the programming language to build your “bridge”
Software engineering is like knowing how to design a bridge. You need to know the proven industry design rules to make a long lasting and reliable “bridge”. In this way you need to learn software engineering to design great software
Learning the Syntax and grammar of a programming language is pretty straight foward [sic!]
Understanding software engineering is the hard part about becoming an iOS developer
Learn BOTH but focus on Software Engieering [sic!]
Software engineering is about the design principles. It’s the necessary condition to plan the components of object-oriented projects like those for iOS and Mac. It is required to write clean code.
Programming itself is about API knowledge, understanding the language grammar and the like.
Of course we write clean code, but we’re able to write it only because we’re able to make a clean design up in the first place. So there’s not much clean coding, but a lot more clean design.
How I prepare Calendar Paste E-Mail Pitches
I’m knees-deep in code and wait for new provisioning profiles from Apple to release an app for Mac next week. Fingers crossed! Meanwhile, I wanted to care for my recently updated Calendar Paste 2 more and reach out to bloggers and the press to increase coverage.
Protocol Madness: Comparing Apples to Oranges from the Vantage Point of Fruit

Brent Simmons starts with Swift. And just as I, he struggles with value types, protocols, and generics: once a protocol references another or has a dependency on Self
, you cannot use it as a type constraint or placeholder for all descending objects. You either have to use generics to expose a variant for each concrete type, or you re-write the protocol. There’s no equivalent to the way Objective-C did this: something like id<TheProtocol>
just doesn’t exist. Swift is stricter. So how do you deal with that?
How to Write Unit Tests for Storyboard-based Buttons in Swift

I’m writing unit tests for my Storyboard-based view controllers. Button interaction can be tested in view automation tests, but that’s slow, and it’s complicated, and it’s not even necessary for most cases. To write unit tests instead of UIAutomation tests for buttons, you test multiple things. Here are the tests.
Using Swift Enums to deal with Storyboard Segues
I like when the code is explicit. Unlike Brent Simmons, I don’t feel comfortable using string literals in code especially not when I’m still fleshing things out and change values in Interface Builder a lot. In Objective-C, I would’ve used plain old constants. For storyboard segues, for example:
So I’ve finished my model, now what?

After working on the model of your app for a while, it can be hard to change your ways of thinking and see what should be coming next. How does an app come out of all this? Where does the user interface plug in? It helps to architect your app in layers and focus on the missing parts before figuring out the glue.
Freemium won’t solve your problems magically

Freemium is said to be a popular way out of the iOS App Store underground. Make your app freemium and skyrocket your downloads. Then sell cool stuff from within the app to unlock more features or buy expendable contents and services.
This doesn’t work for all things on the market, of course.
Shuveb Hussain wrote about his own freemium experiments and that he considers it a failure in his case.
Why did Shuveb’s app make less money with freemium than with a paid-up-front sales model? That’s hard to find out without more experiments, but unlike in science, I guess you can only have that many trials in the App Store before users stop to trust you.
Shuveb himself said multiple times that his app is really really niche-specific. His freemium model allows people to convert one article to Kindle per day for free; more cost money. Maybe his users need no more than one article per day, maybe often times even less. That’s possible but hard to say without analytics about usage patterns from within the app.
Even with app analytics, how can you find out usage patterns if people know they have only one shot per day and probably don’t open the app more often than that?
You can only compare to data from the less limited intro phase. Do users stop opening the app regularly after they converted their first 3 articles?

Read Stuart Hall’s experiments with the vastly more successful 7-Minutes workout app. He switched to In-App Purchases and people loved it. He found folks liked buying features less than buying additional content. I try to keep that in mind because it makes sense, but then again, I’m probably biased towards the good story.
Finding out how to make money with iOS apps is pretty hard. Actually making money is easier if you have a huge following of people you can market to. It’s easier with a network of bloggers and journalists. It’s easy when your app doesn’t actually suck.
Well, of course it’s easier if it isn’t hard.
I believe in value of the craft. I have to in order to stay sane. But crafting alone doesn’t feed hungry mouths. It merely keeps me happy. We need a market, and we need to reach it, and we need to deliver timely. There’s a lot of uncertainty and pressure. Making apps freemium from the get-go might not solve any of our problems. We have to think twice about it, you and I and all the other indie app devs. And maybe hope for a niche of professionals who are willing to pay more. (Which is the other popular promise how to become successful.)
Generics in Objective-C
Objective-C got generics! No more collection classes just for the sake of guarding against invalid elements!
I used custom collection classes a lot for the Word Counter to let the compiler help me prevent mistakes. Swift generics were a godsend for that kind of safety. Now, Objective-C can achieve similar awesomeness.
It can look like this:
@interface Wheel : NSObject
@property (nonatomic, strong) UIColor *color;
@end
@interface Vehicle : NSObject
@property (nonatomic, copy) NSArray<Wheel *> *wheels;
@end
Now the compiler will warn (!) you if you misuse it:
Vehicle *car = [[Vehicle alloc] init];
[car.wheels addObject:@"NSString is of the wrong type"];
Great news, since if you didn’t spend a lot of time creating custom collection types yourself, now at last can you ensure array element type consistency. Makes your code cleaner and more reliable.
Be Cautious with Try-Catch for error handling in Swift 2.0

Throwing exceptions and being able to catch them is awesome news. Then there are cases which can be handled with try-catch technically, but shouldn’t. Think about this: in what cases could you make use of that? And what are the consequences for your work? For example, Erica Sadun points out that accessing array indexes out of bounds as a subscript will still crash the app since you can’t catch that kind of exception (yet).
Test doubles for Core Data managed objects might not work as expected
You don’t have to learn anything new if you work with Core Data in Swift. It’s a pain to use NSManagedObject
directly, so you better work with custom subclasses all the time. Unboxing optional NSNumber
s is just too cumbersome. There are caveats you should be aware of, though: Swift’s static typing makes it a bit harder to write test doubles for managed objects.
State of Mocking in Swift Tests

Mocking and stubbing in tests is useful to verify behavior and replace collaborating objects with simpler alternatives. Since Swift is statically typed, you can’t use a mocking library anymore. But it’s trivially simple to write simple mock objects as subclasses in place:
This is probably the nicest Swift Result enum ever
Until today, I had a regular-looking “fetch all” method on a Repository I am working with. It obtains all records from Core Data. When I discovered the nice Result enum by Rob Rix, things changed. I talked about using a Result enum before, but haven’t used an implementation with so many cool additions.
Observing Enums in Swift 1.2 with KVO
Swift 1.2 brought very nice additions to the functionality of the language. Among one of my favorites is that we can now use Key-Value Observing on enum
attributes. Here’s an example. Capacities of container are pre-set in our domain, so it makes sense to create an enum to represent the allowed values:
Combining Collection-Like Repositories and East-Oriented Code
A repository pattern is used to model a central place in your domain to fetch model instances. It usually hides database-related stuff behind a collection-like interface. You don’t have to worry about caching or database query optimization in client code – the concrete repository implementation will handle that.
Calendar Paste 2.2.0 Release Is Out

After working on it in my spare time for the last couple months, I have released a rather large update to Calendar Paste this week. This update is mostly behind-the-scenes stuff. Visible to the user are a few color changes, and adapting iOS 8 looks better. The app looks nice on iPhones of all sizes available for the first time.
Swift Extensions and Information Hiding
Andrew Bancroft tested and analyzed the behavior of extensions in Swift.
While his findings aren’t utterly surprising, having them summed up in this nicely done article certainly helps.
In a nutshell:
- extensions in the same file as their source can access even
privat
members (attributes and methods, that is) - extensions in different files can access
internal
andpublic
members – but only if they are in the same module - if extensions are in a different module, they merely have access to
public
members - classes with
public
orinternal
visibility on themselves expose their members asinternal
by default - classes with
private
visibility on themselves expose their members as private - extensions themselves don’t have to be
public
forpublic
members to work (unlike classes)
This has consequences for your tests: they reside in a separate module, so they can only access public
members of your classes.
If you extend classes from static libraries, the same holds true. Different module, only public
accessors.
Success and Error Callbacks in Objective-C: a Refactoring
I’m refactoring code of Calendar Paste 2 some more. Since I like what I learned using Swift so much, one of today’s changes was about making a view controller method do less by factoring object creation and error handling into its collaborators. The resulting code handles far less of the action involved. Instead, it delegates the action to a new command-like object. And instead of querying an event template for data and assembling an actual event with start and end dates, it delegates event creation to the template itself. Tell, Don’t Ask saved the day.
Return Types can Capture Async Processes and Failures

I’ve written about using the Result enum to return values or errors already. Result
guards against errors in the process. There’s also a way to guard against latency, often called “Futures”. There exist well-crafted solutions in Swift already.
Book Updates for Swift 1.2
I have just updates the book Exploring Mac App Development Strategies to Swift 1.2. A few sections were expanded, a few paragraphs rewritten – but the big update is still underway. It’s due this summer, and then I’ll consider the book feature-complete. Until then, check out the current deal for Creating Multi-Process Mac Applications, which is available at a discount right now since it’s an early release version.
Functional Programming in Swift (YouTube Videos)

After the latest change in my diet, I eat a lot more often throughout the day and try to spend the time watching educational talks to make use of my time. Functional programming seems to not only be all the hype – its concepts seem to reach mainstream thinking, too. Here’s a collection of talks you might find worth your while.
- Functional Swift – conference recordings with tons of great stuff
- Erik Meijer: What does it mean to be Reactive? – taught me a lot about being explicit and honest in my return types
- Neal Ford: Functional Thinking – how to use data transformations instead of a series of instructions
- Erik Meijer: Functional Programming – shows what being stateful entails
If you got some useful talks, share them in the comments!
Event Publisher Revision 1
I have imported my latest event publishing code into the Word Counter. Since the DomainEventType
enum didn’t provide much value besides obtaining a notification name, I decided to get rid of it and obtain a name by another means.
In the current iteration (see the Gist), the event protocol reveals a static eventName
. I also removed the duplicated notification factory from concrete events:
import Foundation
public typealias UserInfo = [NSObject : AnyObject]
public protocol DomainEvent {
class var eventName: String { get }
init(userInfo: UserInfo)
func userInfo() -> UserInfo
}
public func notification<T: DomainEvent>(event: T) -> NSNotification {
return NSNotification(name: T.eventName, object: nil, userInfo: event.userInfo())
}
It’s weird that I have to write notification<T: DomainEvent>(event: T)
to access static properties of the event type. notification(event: DomainEvent)
doesn’t work as of Swift 1.1., because “Accessing members of protocol type value ‘DomainEvent.Type’ is unimplemented”.
In a similar vein, a method like this doesn’t satisfy the generics requirement:
func foo(event: DomainEvent) {
let notification = notification(event)
// ...
}
But this does:
func foo<T: DomainEvent>(event: T) {
let notification = notification(event)
// ...
}
Mixing protocols and generics makes me wonder where the problem lies, but hey, it does work this way, although generics pose a slight performance penalty to protocols if I remember the WWDC talks correctly.
Painless Event Delivery With a Custom Publish-Subscribe Infrastructure

In my apps, I have used a custom event delivery mechanism on top of NSNotificationCenter
with great success: I send a lot more events and consequently decouple parts of my code more easily. Putting your own objects around the Cocoa foundation can help use them more often. I want to show you how my EventPublisher
works, and why custom event types make me send a lot more events than when I only had NSNotification
s.
Save Your Butt in Unit Tests With Shallow Reaching
I assume you do write tests. To test system boundaries, you have to find out whether methods are called. Usually, people reach out for mocks to verify behavior.
If you use a lot of mocks, though, the tests can reveal high coupling in your code: either you have to mock objects multiple levels deep, which is a sign of too much knowledge about how the collaborating objects work, or you have to mock lots of objects one level deep. The latter can be acceptable when you test a components which is some kind of coordinator. The former, though, is never to be accepted. Use the feedback of these hard-to-write tests to make your code simpler.
That’s what the Law of Demeter is for. While “law” is way too strict, its principle is sound: strive to call methods on the objects you have direct access to, but avoid calling methods on objects which you obtain through another method call in the first place.
For example, the following violates the principle:
func violateThePrinciple(aCollaborator: Collaborator) {
let aStranger = aCollaborator.obtainFriend() // this is okay so far
aStranger.doSomething() // this is not, because it's 2nd level
}
You can get by through providing facade methods:
func respectThePrinciple(aCollaborator: Collaborator) {
aCollaborator.doSomething()
}
extension Collaborator {
func doSomething() {
self.friend.doSomething()
}
}
In your unit tests, you can add a Collaborator
mock to verify the calls and then you’re good to go. No multiple levels of mock objects and stubs. You may call this “shallow reaching” (opposed to “deep reaching”), although no one else calls it that.
That’s the Law of Demeter in a nutshell: only talk to friends which you know through properties or parameters, but don’t talk to strangers which you get to know through the return values of your friends’ methods. You never know what to expect.
Zettelkasten Posts Moved
Since we started the Zettelkasten blog, it became weirder and weirder to keep the old posts here. I found the split among domains unfortunate.
Today, I’ve moved all Zettelkasten-related posts to the project blog at Zettelkasten.de. The old addresses won’t change, and your comments have persisted, too.
Thanks for visiting this blog, and thanks for caring about what I write! If you’re still interested in personal information management, head over to the new place. If you’re into programming, though, stay here.
VIPER iOS App Architecture Approach


Ryan Quan of Brigade Engineering has published an article about using the VIPER iOS app software architecture. Their write-up is really good: message passing is illustrated with code samples – and they even use neat box graphs!
I use a VIPER-like approach in my apps, too, and I’d like to invite you to try it for yourself. VIPER is inspired by Clean Architecture and Hexagonal.
In a nutshell, you decouple the view controllers from event handling from data management. You introduce so-called “Wireframes” to set up a module or “stack” of objects to display a view controller with certain data. The Wireframes set up everything once. Afterwards, event handlers take over, called “Presenters”. They perform transitions between scenes. View controllers do not much more than setting up the view and reacting to IBAction
s.
This will make maintaining code easier because the view controllers are finally put on a diet. Figuring out how data has to flow differently takes some getting used to. I’m going to write about this in a future post.
3 Ways to Model Relationships in a Domain
Let’s assume we need a Domain Model and can’t create our application with basic CRUD actions and data containers. Let’s further assume we have a Box
Entity which can contain many Item
n. Item
is an Entity, too, because its attributes may change over time, so a Value Object won’t do.
Split Commands and Informational Return Values Apart Using Events
When you reason about objects in your system and their means of communication, you can differentiate between three messaging flavors according to Mathias Verraes: imperative, interrogatory, and informational messages. Before we can talk about informational messages and their value, let’s recap the other two and see what the difference is, because them calling for being extracted is not easy to spot.
Going Beyond Guard Clauses in Swift

Erica Sadun brought up a topic which is bugging me for some time already. It’s how Swift encourages you to handle optionals. It’s related to handling exceptions, which I covered earlier. Either you use if-let
to unwrap them implicitly and do all the stuff inside the nested code block, or you end up with code which is a lot wordier than I’d like it to be.
Plug-in a UITextView Placeholder Label Extension

Kevin McNeish created a Swift extension for UITextView
to show a placeholder text when a text field is still empty. It takes all the burden from the view controller and is a real plug-in: it won’t interfere with existing code and only requires you add the file to your project. That’s it.
Functional Error Handling in Swift Without Exceptions
In Swift, there’s no exception handling or throwing. If you can’t use exceptions for control flow like you would in Java, what else are you going to do if you (a) write library code which executes a failing subroutine, and (b) you find unwrapping optionals too cumbersome? I played with the thought of keeping Swift code clean, avoiding the use of optionals, while maintaining their intent to communicate failing operations.
Use Double-Dispatch and Polymorphism to Get Rid of Conditionals
I want to point out a particular refactoring Jimmy Bogard shows in his video I mentioned last time. Jimmy transforms a switch
statement into a double-dispatch method call, making use of good old polymorphism to deal with variety of options. We’ll see what these terms mean when applied.
Crafting Wicked Domain Models by Jimmy Bogard

When we create applications and the business logic becomes more complex, it might be a good idea to focus on moving business logic into the Domain Model intentionally. If you don’t do this, business logic will likely bleed into view controllers. Good luck finding the scattered remains when you need to perform changes!
Thinking in Terms of Functional Programming Encourages Clean Factoring of Code
Chris Eidhof provided an excellent example for creating a mini Swift networking library. It executes simple requests and can be extended to work with JSON (or XML, if you must) without any change. The accompanying talk is worth watching, too. You should check it out to see well-factored Swift code in action. It’s a great example.
How John Sonmez Helped Me Streamline This Blog

I’m going to change things here a little bit in the upcoming weeks. Recently, I found out what I want to do with this blog. John Sonmez of Simple Programmer is offering a free three-week e-mail course for starting to blog as a software developer. I subscribed to check out what other developers on the web do, and I have read his 6 e-mails and followed some of his advice. One particular e-mails made me think about my projects, what they mean to me, and how they relate to each other.
How to Resolve Word Counter Update Issues

Users have reported update problems after they purchased the Word Counter for Mac.
I am aware of this issue. The easiest fix is to download the latest version (.zip
, 2.3 MB) yourself manually.
The version you got from the store cannot recognize more recent versions as valid, so it rejects the update. Maybe I can find a way to fix this on my side, soon. I pushed an update to the store already.
This is very unfortunate, and I’m very sorry for the trouble this has caused.
All the best to you,
– Christian
Model–View–View Model (MVVM) Primer

This is an excerpt of my book “Exploring Mac App Development Strategies”, on a sale right now! I learned that the “view model” in the architectural style of MVVM is a “model of the view” instead of a “model for the view”. Let me explain the difference and the benefits of being able to chose between both.
Getting XPC to a Helper App Working with Sandboxing Enabled
Here’s how I fixed the inter-process communication sample app called AppSandboxLoginItemXPCDemo by Apple to make it work. When I tried it out at first, sandboxing ruined the day. You have to change a few things in order to make it work.
Subscribe to My New Mailing List
I have a Zettelkasten project newsletter for a few years already, and it was featured on this site as I wrote about the topic.
Since my endeavors on this worklog/blog have shifted, I think it’s the right moment to offer a non-Zettelkasten newsletter for the folks interested in my projects, the programming books, and the software I develop.
The new project newsletter will be my premier place for project announcements and software beta invitations. A lot of you have helped already make the Word Counter better. There’ll be lots of opportunities to test software for free in the future. There’s a bunch of stuff in the making.
Apart from project updates, I’ll provide a convenient list of posts I have published on all my project websites since the previous issue so you don’t have to collect these, too.
Thanks for your support and for reading this blog! If you want to stay up to date and benefit from a much closer contact, sign up now.
Storyboard Segues VS Tell Don’t Ask Principle
UIStoryboardSegue
s are a blessing to add rudimentary navigation between view controllers in iOS projects. User interaction can trigger segues without any code. That’s all good and well to move back and forth between mostly static scenes in your Storyboard. Passing data around is not so easy, though, without making things more complicated.