A Vacation Week – 20% Discount While I’m Away!

palm trees
vaycay by Philipp Richter. License: CC-BY-NC 2.0

I’ll be on vacation for the next week. Maybe I cannot hold my breath and publish a post nonetheless, but I’ll try not to. Either way, for the next week everything from my store is 20% off so you can have fun while I’m away.

Apps

  • The Word Counter to increase writing productivity,
  • Move! to not die from sitting in front of your computer.

Books

Enjoy the new and shiny Indie Mac Developer book bundle, including:

– both of which you can buy on their own, too, of course, if you don’t need both.

Not related to programming but rather writing: Minimal Writing on the Mac, too, is on discount.

Reusable View Components from Nibs

Just found this today in a Slack channel. It seems we can actually reference and re-use Xib files by overriding awakeFromCoder!

If we are loading from placeholder view, we create a real view and then we transfer some common properties from it and all it’s subviews, then we just return that instance in place of placeholder, otherwise we just return normal view (This method is implemented on NSObject so we can call super, but this still should be done with method swizzling instead of category smashing).

There’s a sample project on GitHub. Let’s tear it apart.

It works like this:

const int kNibReferencingTag = 616;

@implementation UIView (NibLoading)
// ...
- (id)awakeAfterUsingCoder:(NSCoder *)aDecoder
{
  if (self.tag == kNibReferencingTag) {
    //! placeholder
    UIView *realView = [[self class] loadInstanceFromNib];
    realView.frame = self.frame;
    realView.alpha = self.alpha;
    realView.backgroundColor = self.backgroundColor;
    realView.autoresizingMask = self.autoresizingMask;
    realView.autoresizesSubviews = self.autoresizesSubviews;

    for (UIView *view in self.subviews) {
      [realView addSubview:view];
    }
    return realView;
  }
  return [super awakeAfterUsingCoder:aDecoder];
}

When the kNibReferencingTag is set, the current instance (self) is treated as a prototype. From that prototype we transfer common properties to the realView which is properly loaded from a Nib. That means it doesn’t go the kNibReferencingTag path but the usual path, deferring to super.

The sample app contains SomeView with its own Xib that should be reused.

In the app’s Xib, we have a scene that uses it as follows:

<scenes>
    <!--View Controller-->
    <scene sceneID="4">
        <objects>
            <viewController id="2" customClass="ViewController" sceneMemberID="viewController">
                <view key="view" contentMode="scaleToFill" id="5">
                    <rect key="frame" x="0.0" y="20" width="768" height="1004"/>
                    <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                    <subviews>
                        <view tag="616" contentMode="scaleToFill" id="VTu-Cz-9kE" customClass="SomeView">
                            <rect key="frame" x="113" y="216" width="100" height="100"/>
                            <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                            <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
                        </view>
                        <view tag="616" contentMode="scaleToFill" id="7te-Q6-moz" customClass="SomeView">
                            <rect key="frame" x="199" y="446" width="100" height="100"/>
                            <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                            <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
                        </view>
                        <view tag="616" contentMode="scaleToFill" id="7vx-xh-xRD" customClass="SomeView">
                            <rect key="frame" x="375" y="231" width="100" height="100"/>
                            <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
                            <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
                        </view>
                    </subviews>
                    <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
                </view>
            </viewController>
            <placeholder placeholderIdentifier="IBFirstResponder" id="3" sceneMemberID="firstResponder"/>
        </objects>
    </scene>
</scenes>

I know, Xib files aren’t the best to read. Here’s what it boils down to:

  • Create a scene using a view controller of type ViewController.
  • In its main view place 3 subviews …
    • of type SomeView,
    • all with the tag 616,
    • and a few standard color properties – apparently all set to white. It doesn’t matter anyway since the SomeView.xib will dictate what it really looks like.

Unlike @IBDesignable components, you won’t have any live preview in Interface Builder. Just empty placeholder boxes.

Featherweight Router

I read Karl Bowden’s Featherweight Router TL;DR and kind of like how routes are handled. The setup looks complicated, though:

let someRouter = Router(aDelegate).route("animal", children: [
    Router(aDelegate).route("animal/mammal", children: [
        Router(aDelegate).route("animal/mammal/cow"),
        Router(aDelegate).route("animal/mammal/pig"),
    ]),
    Router(aDelegate).route("animal/fish", children: [
        Router(aDelegate).route("animal/fish/salmon"),
        Router(aDelegate).route("animal/fish/trout"),
    ]),
])

// Using regex's for matching
let someRouter = Router(aDelegate).route("animal", children: [
    Router(aDelegate).route("animal/\\w+", children: [
        Router(aDelegate).route("animal/\\w+/\\w+")
    ])
])

Child routers carry the path component of the parent with them. Also, this is very verbose. I imagine a more terse version, like:

// Assuming `aDelegate` is used for all of them and passed along,
// let's omit it during setup of sub-routes:
let router = Router(aDelegate) { router
    router.route("animal") { router in
        router.route("mammal") { router in
            router.route("cow")
            router.route("pig")
        }
    }
}

Or let’s say some part is variable, like viewing a user profile:

let userRouter = Router(aDelegate) { router 
    router.route("users") { router in
        router.route(.Parameter("userId", "[0-9]+")) { router in
            router.route("friends")
            router.route("photos")
        }
    }
}

Then the route users/12345/friends will parse and the “12345” part will be available in a params dictionary under the key userId.

I haven’t given routers much though in the past but I think I’ll explore the possibilities of routing and existing libraries some more.

Import Parts of a Module

Did you know you can import only parts of a module? Found this in the Swiftz sample codes:

let xs = [1, 2, 0, 3, 4]

import protocol Swiftz.Semigroup
import func Swiftz.sconcat
import struct Swiftz.Min

//: The least element of a list can be had with the Min Semigroup.
let smallestElement = sconcat(Min(2), t: xs.map { Min($0) }).value() // 0

import protocol or even import func were very new to me. Handy!

rethrows in Swift

Rethrows saves us a lot of duplicate code. Look at my naive approach to write an iterator in Swift 1 from last year which I later extended for throwing with Swift 2:

extension Array {
    func each(@noescape iterator: (Element) -> Void) {
        for element in self {
            iterator(element)
        }
    }
    
    func each(@noescape iterator: (Element) throws -> Void) throws {
        for element in self {
            try iterator(element)
        }
    }
}

This can be written as a single method with Swift 2 as I later found out:

extension Array {
    func each(@noescape iterator: (Element) throws -> Void) rethrows {
        for element in self {
            try iterator(element)
        }
    }
}

The rethrows keyword makes the method a throwing one depending on the closure you pass in. Only if the closure throws each will throw, too. The compiler will know what happens – just like generic functions are write-once, use-many-times.

Of course I later found out that Swift 2 came with forEach already bundled in. So there’s no use in this anymore except for this very illustrative blog post to remember that throws/rethrows is different from throws/throws.

How do You Really Mock Objects You Don’t Own? You Replace Them with Adapters

Teaser image

How do you test NSURLSession properly? After all, using it in tests directly will hit the servers; that’s not what you want to do 1000s of times per day. Even if you use a localhost based server replacement the tests will be slower and potentially error-prone as the server replacement may not be 100% accurate. Anyway – there’s a popular series of posts about that topic. There, you’ll learn how to mock NSURLSession in your tests. I think the advice is good to move on quickly, but it only shifts the problem slightly out of sight. There are better alternatives.

Continue reading …

DevMate is Completely Free Now

When DevMate launched, I dabbled with the backend a bit and I really liked it. They use FastSpring for the store and enabling DevMate to integrate into your FastSpring account is very simple.

It seemed to be kind of expensive, though. Since then, they changed the pricing model once or twice and made the platform more attractive to upcoming indies and teams with a lower budget. Now it’s free.

Their SDK seems to provide easy integration. I think I’ll check it out with my next app to tell you more about the details. I just hope they’re doing well – lowering the price could just as well mean that they try to attract more devs because it doesn’t pay off to run the platform at the moment. (I think I’ll just ask them to be sure.)

Piezo Exits the Mac App Store

Rogue Amoeba develop lots of popular software. Now Piezo 1.5 exits the Mac App Store.

While the App Store has many shortcomings, it’s the onerous rules and restrictions Apple has for selling through the Mac App Store which pose the biggest problem. The type of software we make is precluded from being sold through the store, particularly now that sandboxing is a requirement, and Apple has shown no signs of relaxing those restrictions. Fortunately, unlike iOS, the Mac platform is still open. We’re able to distribute and sell direct to our customers, right from our site. We’ve got almost 15 years of experience and success doing just that, and we have no plans to stop.

Their apps that work on the App Store stay there.

Shameless self promotion: Are you worried about the recent trend of abandoning the MAS? I wrote a book about publishing apps outside the Mac App Store. There’s nothing you have to fear. It’s fun.

Publish and Subscribe — Decoupling Deep View Hierarchies from Event Handlers

Imagine a complex view with many sub components. This is more common in Mac apps where a window contains multiple panes, lists, graphs, whatever. How do you react to interactions 5 levels deep? Let’s say you avoid massive view controllers which do everything on their own and want to encapsulate event handling outside the view hierarchy – what should you do?

Continue reading …

Extract Private Functions as Collaborators

“Using a private function means having a hardwired link to an anonymous collaborator. Over time, this will slowly hurt more.” (@jbrains) I was thinking about this the other day when I wrote tests for a presenter. It receives a date, formats it, and makes the view update a label with the result. Simple. (The real thing actually does a bit more, but that doesn’t matter much.)

Continue reading …

Symmetry

At first, this was all there was:

protocol DisplaysDateRange {
    func showDateRange(dateRange: DateRangeData)
}

class DateRangeViewController: NSViewController, DisplaysDateRange {
    @IBOutlet var dateRangeButton: NSButton!

    func showDateRange(dateRange: DateRangeData) {
        dateRangeButton.title = dateRange.range
    }
}

Then I implemented a sub-view controller and delegated to it, too:

class DateRangePickerController: NSViewController, DisplaysDateRange { 
    // ... 
}

class DateRangeViewController: NSViewController, DisplaysDateRange {
    @IBOutlet var dateRangeButton: NSButton!
    @IBOutlet var dateRangePickerController: DateRangePickerController!

    func showDateRange(dateRange: DateRangeData) {
        dateRangeButton.title = dateRange.range
        dateRangePickerController.showDateRange(dateRange)
    }
}

Then, by habit, I remembered Kent Beck’s advise to keep symmetry high for clean and maintainable code:

class DateRangeButton: NSButton, DisplaysDateRange {
    func showDateRange(dateRange: DateRangeData) {
        title = dateRange.range
    }
}

class DateRangeViewController: NSViewController, DisplaysDateRange {
    @IBOutlet var dateRangeButton: DateRangeButton!
    @IBOutlet var dateRangePickerController: DateRangePickerController!
    
    func showDateRange(dateRange: DateRangeData) {
        dateRangeButton.showDateRange(dateRange)
        dateRangePickerController.showDateRange(dateRange)
    }
}
petals
Photo credit: Layers of petals by n.a.t.u.r.e. License: CC BY-NC-ND 2.0

Sure, now there’s a subclass of NSButton that doesn’t do much and will not be reused in the app. But the intent of delegating DateRangeData to the sub-components is clearer.

Clean and maintainable code will help you see what’s going on when you read the code. title = dateRange.range doesn’t convey everything showDateRange(dateRange) does.

1 Criterion to Determine if You Should Write Unit or UI Automation Tests

Teaser image

Xcode now offers two kinds of tests natively. You don’t have to rely on 3rd party JavaScript libraries anymore to automate the iOS simulator and assert view conditions. So with the advent of native UI Automation tests, can you rely on them to verify your app works? Here’s the two sides of the 1 criterion you’ll ever need to find out:

Continue reading …

Always Write Functions to Cope with all Possible Parameter Values

Matt Galagher is back writing at Cocoa with Love. His goal is maintainability, which is the greatest of all, I think. It’s easy to copy code samples together to create an app, bur it’s hard to create a product you can keep alive and make better over years. In that vein, his first article, “Partial functions in Swift, Part 1: Avoidance”, includes a lot of details why partial functions will hurt you. This is a great topic. Read his post for the basic set theory involved.

Continue reading …