Archive for February 2015

Saturday, February 28, 2015

Core Data vs. ARC

Matt Drance:

1) Create NSManagedObjectContext

2) Fetch

2) Pass results to a method

I’ve seen ARC kill the MOC before line 3.

With at-autoreleasepool, you could optimize given advanced knowledge. Now you need advanced knowledge to not die.

The problem here is that Core Data expects that you will keep the managed object context alive as long as you are using any of its objects, but the objects do not retain their context:

Managed objects know what managed object context they’re associated with, and managed object contexts know what managed objects they contain. By default, though, the references between a managed object and its context are weak. This means that in general you cannot rely on a context to ensure the longevity of a managed object instance, and you cannot rely on the existence of a managed object to ensure the longevity of a context.

ARC will try to release the context after the last line of code that references it, even if this is before the end of the scope. (This is different from other automated reference counting systems, such as Python’s.) It doesn’t know that later code in that scope may use managed objects that assume their context is still alive. This was also a problem with Objective-C garbage collection; Core Data used weak references even though the collector could have cleaned up cyclic strong ones.

Some potential solutions:

All of this makes me sad because something this basic should not be so error-prone, and it should not be getting worse with time. As Drance notes, all of this just worked with manual reference counting. An autoreleased context would automatically stay alive as long as it was needed. You could fine-tune object lifetimes for increased performance; now you have to do so to avoid crashes.

Arguably, this is a design flaw in Core Data rather than ARC. Why don’t objects retain their context?

As far as I can tell, the situation is actually worse with Swift. It uses ARC but doesn’t seem to have the equivalent of NS_VALID_UNTIL_END_OF_SCOPE.

Friday, February 13, 2015

Swift 1.2

Apple:

Today Swift 1.2 was released as part of Xcode 6.3 beta. This beta release includes a significantly enhanced Swift compiler, as well as new features in the Swift language itself. For the complete list of changes, read the release notes.

There’s lots of good stuff here, and it’s really impressive how quickly Apple is moving. Some highlights are performance improvements (especially with the optimizer off), a set data type, and a fix for the pyramid of doom.

Greg Heo:

In Swift 1.2, Objective-C classes that have native Swift equivalents (NSString, NSArray, NSDictionary etc.) are no longer automatically bridged. That means passing an NSString to a function that expects a String will now fail!

[…]

If you’re maintaining Objective-C code, there are some new qualifiers for you to use when specifying the type for arguments, variables, properties, etc. […] If you don’t have Objective-C code to maintain, you’ll still benefit from Apple adding these qualifiers to the Cocoa headers. That will make your Swift experience that much cleaner with fewer implicitly-unwrapped values.

Nate Cook:

Annotating any pointer in an Objective-C header file causes the compiler to expect annotations for the entire file, bringing on a cascade of warnings. Given that most annotations will be nonnull, a new #pragma declaration can help streamline the process of annotating existing classes. Simply mark the beginning and end of a section of your header with #pragma clang assume_nonnull begin and ... end, then mark the exceptions.

Airspeed Velocity covers changes to the standard library, such as:

Since classes in Swift are reference-counted, it ought to be possible to detect if your buffer class is being referenced by more than one struct. But there wasn’t an easy Swift-native way to do this, until 1.2, which introduces isUniquelyReferenced and isUniquelyReferencedNonObjC function calls[…]

Erica Sadun:

Swift now supports building targets incrementally. HELLS yes. It no longer should re-build every single file every single time you add a new punctuation mark somewhere.

Jonathan Wight:

Swift’s new (NS-less) arrays no longer work with KVO.

To be expected but rather annoying.

Yeah so Swift NS-less arrays are really the kiss of death to Cocoa bindings in Swift.

Wil Shipley:

Swift 1.2: my code code runs up to 10x faster than 1.1 unoptimized, up to 8x faster optimized.

David Owens II:

[Optimized] builds were still 2x~4x as slow as C in my limited tests.

David Owens II:

Swift is getting better and faster but it’s still not suitable in the domain space I’m currently working in for this project: high-performance, real-time systems.

Jonathan Wight:

On 1.2 Release is about 180-200% faster than Debug.

IIRC 1.x showed larger differences between debug & release.

Adam Kaplan finds that it’s faster, though still slower than Objective-C:

At this stage I’m more than happy to retract my previous conclusion of Swift being too slow for production use. Swift 1.2 seems more than up-to the task and if they keep updates like this one coming, it may even eventually live up to its namesake.

It still has exponential compile times for simple literals, IDE crashes, and there are some new NSString bridging issues.

Wil Shipley:

In 1989 I saw Cocoa (nee NeXTstep) and said, “I’ll spend my life making it so everyone can use this.”

I feel that was about Swift, now.

Update (2015-03-10): Douglas Gregor (via Ken Ferry):

In a recent version of Xcode, Apple introduced an extension to C/C++/Objective-C that expresses the nullability of pointers in the type system via new nullability qualifiers . Nullability qualifiers express nullability as part of the declaration of strchr.

[…]

We’d like to contribute the implementation (and there is a patch attached at the end), but since this is a nontrivial extension to all of the C family of languages that Clang supports, we believe that it needs to be discussed here first.

Update (2015-03-12): Apple:

In general, you should look at nullable and nonnull roughly the way you currently use assertions or exceptions: violating the contract is a programmer error.

[…]

Nullability annotations for C and Objective-C are available starting in Xcode 6.3. For more information, see the Xcode 6.3 Release Notes.

Tuesday, February 10, 2015

Snowsemite

Mark Gurman:

Following the success of OS X Snow Leopard for Macs in 2009, one of iOS 9’s standout ‘features’ will be a directed focus on stabilizing and optimizing the operating system.

[…]

For 2015, iOS 9, which is codenamed Monarch, is going to include a collection of under-the-hood improvements. Sources tell us that iOS 9 engineers are putting a “huge” focus on fixing bugs, maintaining stability, and boosting performance for the new operating system, rather than solely focusing on delivering major new feature additions. Apple will also continue to make efforts to keep the size of the OS and updates manageable, especially for the many millions of iOS device owners with 16GB devices.

Clark Goble:

The reason people have such fond memories of Snow Leopard is because they are colored by the end of its life and not its beginnings. But it’s hardly fair to compare 10.6.8 to 10.10.0 or even 10.10.2 (that just came out last week).

I do think it’s a fair criticism that upgrades started coming faster with Lion. Snow Leopard came out August 28, 2009. Lion came out July 20, 2011 nearly two years later. However Mountain Lion came out July 25, 2012, only a year later. It’s been around a year for each release since. That is we no longer have the stability of a year with a solid mature OS with most of the major bugs fixed.

In my recollection, Snow Leopard also started out with fewer bugs than Leopard.

Turning Google Into a Dumb Pipe

Jared Newman:

And yet, when you consider everything Microsoft has said and done over the last year, under CEO Satya Nadella, the company’s new strategy goes deeper than pushing its own services on rival platforms. What Microsoft really wants to do—and what apps like Sunrise and Acompli enable—is to create a new kind of service that sits above all the others. Essentially, it’s trying to turn its cloud competitors into dumb pipes.

[…]

In both cases, you can use those additional services regardless of who’s providing your email or calendars. The fact that you’ve hitched your wagon to iCloud mail or Google Calendar ceases to matter. Acompli’s new Outlook branding seems symbolic in that regard; to Microsoft, all email is now Outlook, even if it comes from another company’s servers.

Wayne Caswell:

Microsoft can overlay Apple and Google to add functionality, but keeping it all working well as Apple and Google evolve their own products and strengthen competitive barriers to entry will be a nightmare. These companies won’t stand still.

Matt McLarty:

The “dumb pipe” situation arises when a company gets caught between two smart endpoints. For example, telcos are continually trying to elevate themselves from dumb pipe status, but struggling in the face of companies like Apple (iPhone at one end, iTunes at the other). In this case, Microsoft is implementing the user-facing endpoint, but relying on smart endpoints like Gmail and Evernote, most likely through their APIs that have implicit terms and conditions. Those endpoints are beyond Microsoft’s control, unless they play dirty and try to hack around them, as pointed out in one of the other comments here. Very shortsighted.

Sunday, February 8, 2015

Photos for Mac

Joe Rossignol:

Following the release of the first OS X Yosemite 10.10.3 beta to developers this afternoon, the embargo has lifted for media outlets to publish their first impressions and hands-on reviews of the all-new Photos for OS X app. Below is a roundup of some of the more interesting comments and opinions about Photos for OS X, which combines iPhoto and Aperture into one for OS X Yosemite.

David Pogue:

In a couple of months, Apple will abandon iPhoto and replace it with a completely new program for OS X Yosemite called Photos for the Mac. Apple has also stopped work on Aperture, its professional photo app, although Apple says that Photos isn’t meant to be its replacement.

[…]

Whenever you’re looking at a tiny grid of tiny thumbnail images (in a Year, Collection, or Moment), you can hold your mouse down within the batch. A larger thumbnail sprouts from your cursor, and you can slide around within the mosaic to find a particular photo, or batch of them.

[…]

Here’s a slick trick: If you drag a photo into several albums, then editing it changes that photo everywhere. But if you copy and paste a photo into a different album, you can edit the individual photos independently. And as a bonus, doing this does not use up any more disk space.

[…]

If you’re worried about fitting an entire library of photos on a device that doesn’t have a ton of storage, like an iPhone or a MacBook Air with a small solid-state drive, you can turn on an ingenious feature called Optimize Mac Storage. It kicks in only when your photo collection becomes too big to fit. At that point, your original photos and videos get backed up to iCloud as usual, but not stored the same way on your phone or laptop. There, the Photos apps get much smaller versions. They give you enough resolution to view on the screen, but not enough to print.

Derrick Story:

We knew there would be some compromise when Apple folded its high-end Aperture and consumer iPhoto applications in to one program. Now that we have an official preview of Photos for OS X, we can see the direction they’re heading.

[…]

We do see some indicators, however, of the direction Apple is taking with Photos. And hardcore Aperture users will surely miss its advanced editing tools. In this area, I would say that early versions of Photos will feel more like iPhoto than Aperture.

My advice is for Aperture photographers to think about a 2-part strategy: what to do for 2015, then 2016 and beyond. For the remainder of this year, we have the luxury of sticking with Aperture on Yosemite and playing with Photos for OS X when it’s released. By the end of 2015, we all should have a pretty good idea of how the new software is going to stack up against Aperture.

Christopher Breen:

When you install Photos you’ll be offered the option to import your iPhoto library. (If you have more than one iPhoto library, Photos will ask you to choose one to import.) You can also import an Aperture library.

Opening one of these libraries in Photos doesn’t duplicate your existing images. You won’t find one set of images in an iPhoto library and another in a Photos library. Instead, the apps will look for images within a single library. Additionally, iPhoto and Aperture don’t become unusable after you’ve launched Photos. You’ll be asked which app you’d like to use with your images. You can choose iPhoto, if you like, with the caveat that any edits you make in a particular app—iPhotos or Photos—will appear only within the app you used to apply them. So, if you convert an image in Photos to black and white and then open that same image in iPhoto, you’ll see the unedited original color version.

iPhoto events and Aperture projects are converted to albums as neither of these items exist in Photos. Metadata including star ratings, flags, and color labels will be transformed into keywords and become searchable in Photos. Other IPTC metadata such as copyright, contact, and content data is retained as part of the image, but it’s not visible within Photos. Custom metadata fields aren’t transferred to Photos.

Christina Bonnington:

So what doesn’t Photos have? Photos does not have things like the granular Precision Brushes feature of Aperture. It does offer a retouching tool. Using that, you can adjust the size of the touch-up brush, but you don’t get to adjust the softness or the strength of this brush, or use the “Detect Edges” feature. As only an occasional Aperture user myself, I suspect there are other advanced adjustments professionals may notice missing, as well.

Serenity Caldwell:

Just like iPhoto, the Photos app supports opening and working with multiple libraries, but you won’t be able to unify multiple libraries within it.

That means that once you pick, say, your iPhoto library, you can’t import an Aperture library into that new Photos library. You can, however, create a separate Photos library (by holding down Option when launching the program) and import your second library into that.

If you want to unify your photos, we suggest combining your libraries into one master Aperture library first.

[…]

There’s a setting you can uncheck to just link to your photos in their existing locations, rather than directly importing/duplicating them.

[…]

[Stacks, Projects, and Events are] all converted to Albums (and folders holding albums) so that you don’t lose any of your prior organization. These albums are Mac-only, however; they don’t sync with your iOS devices.

[…]

My Photo Stream — which uploads the last 1000 photos (or 30 days’ worth) to the cloud and your Mac for free — is alive, well, and continuing into the foreseeable future with no plans on Apple’s part to change it. If you have iCloud Photo Library enabled, it will sidle off into the background and you shouldn’t really notice it. Those who choose to keep iCloud Photo Library disabled, however, will still see the My Photo Stream option.

Fat Cat Software:

My hope in the long run is to be able to have iPLM do all the same things it currently does with iPhoto libraries, but with Photos libraries as well. This includes things like copying between libraries, merging libraries together, eliminating duplicate photos, and so forth. It’s still too early to tell exactly what features we’ll be able to support with Photos though.

Update (2015-02-13): Jason Snell:

Photos feels more like the Mac version of the iOS Photos app than either iPhoto or Aperture, at least when browsing your photo library. Zooming out (which you can also do with a pinch on the trackpad) presents you first with a series of short events defined by location. Zoom further out and you’ll see larger spans of time and a list of locations. One more zoom and you’re left with a giant wash of photos separated by year.

[…]

If you want to edit your photo in an external tool such as Photoshop, there appears to be no way to do that, at least in this beta, beyond dragging an image out, editing it, and then dragging it back in. Here’s hoping Apple allows an external-editor feature or support for image-editing extensions of some sort in the future.

[…]

Never say never, but in my tests with a 5,450-image library, Photos seemed downright fast. Scrolling never lagged. Zooming in and out was speedy.

Jason Snell:

How can it not duplicate the photos, yet not risk losing all your data if you were to throw away your old iPhoto library? […] It creates hard links to the contents of your iPhoto library inside the Photos library. If you delete your iPhoto library, the files that were hard-linked from the Photos library still exist in the Photos library and aren’t deleted.

[…]

So what happens if you edit one of those files? Something very clever, it turns out: If I open the JPEG image from the migrated iPhoto library in Photoshop, edit it, and save it, that version is indeed altered—but the version in the Photos library is untouched. Basically, modifying that file causes the link between the two versions to break. They’re different, and no longer connected.

Jason Snell:

iPhone burst mode photos come in as stacks. If you take 50 photos in a very short amount of time with an SLR, though, those seem to just come through as a whole bunch of individual pictures.

[…]

As of this beta, you can sync everything in the system Photos library, or nothing. That’s it.

Joseph Linaschke:

When we first started talking about this last year, the discussion was that 3rd parties would be able to expand Photos by use of an Extensions architecture, allowing them to fill in the gaps, at least for editing, that Apple left behind. This is still the idea, however we will not be seeing this in Photos 1.0.

[…]

What I’m more concerned with is the missing features that I don’t see any value to Apple to add back in that a small but vocal group of us absolutely need in a professional photo editor. Renaming files on import. Custom metadata fields. Custom metadata views (both in a metadata window and overlaid on the photo itself). Scripting support (AppleScript support is present, but not as robustly as in Aperture). Batch processing. Custom export presets. Hierarchical keywords. Exporting of projects as libraries. Merging of libraries with intelligent duplicate handling. Opening in external editor apps (like Photoshop) with complete round-trip support. Tethered shooting. Stacks. Date and time correction (Date and time correction is in Photos 1.0). Compare view modes. Lift and stamp (Lift & Stamp is also present, however can currently only do one at a time). Multi-card import. Backup on import. And a whole lot more.

[…]

Last year, I was bullish on Photos eventually replacing Aperture. I no longer feel that way. I am sure it will be a great app — a really great app. And I’m sure that it will have enough features for the vast majority of users. […] Plainly put — I no longer believe that serious Aperture users should expect Photos to replace their photography management and editing needs. I am now recommending that advanced and professional users begin to explore other options.

Recover Data Lost Because of iCloud Sync Problems

Kirk McElhearn:

So, there are a couple of morals to this story. First, don’t trust iCloud. I don’t blame Realmac; it’s probably not their fault. I find it interesting that the data loss occurred overnight; I may have looked at my Clear list on my iPad yesterday evening, but I don’t recall doing so. If I had, I would have spotted that a list was missing. So my guess is that the data loss is due to iCloud itself.

Second, don’t use an app that doesn’t offer backups. I looked in my local folders and couldn’t find any readable files that I would have been able to recover from Time Machine backups. There’s a locally-stored .sqlite file, but it doesn’t contain the same data.

I won’t be trusting any important data to iCloud any more. I am slightly concerned about my contacts; I’ve had issues with them in the past. I know there are local and Time Machine backups that I could restore if I ever need to. But for the rest, iCloud is simply too precarious.

He used iExplorer to get the Core Data SQLite database out of his local iTunes backup.

Google 2-Step Verification in Mac OS X 10.10.3

Eric Slivka:

On OS X 10.10.2 and earlier, users setting up their machines to access Google accounts with 2-Step Verification enabled have had to use this app-specific password option. Users trying to log in with their standard Google account passwords are met with error messages informing them they need to use this option.

[…]

But as noticed by developer Jonathan Wight, the new OS X 10.10.3 beta now fully supports 2-Step Verification, allowing users to log in with their standard passwords and unique verification codes.

I guess Apple really does like embedded browser views.

Better Emoji in Mac OS X 10.10.3

Eric Slivka:

One immediately evident change is the menu option used to bring up the character palette where emoji and other symbols can be browsed and selected. The Character palette a is systemwide option generally accessed through the “Edit” menu in most Mac apps. On OS X 10.10.2 and earlier, the menu item is called “Special Characters,” while on OS X 10.10.3, it is labeled “Emoji & Symbols”. The change offers a clearer description of what can be accessed through the menu item while specifically giving a strong visibility boost to emoji.

Another significant change for emoji in OS X 10.10.3 is the apparent laying of groundwork to support skin tone modifiers proposed for the Unicode 8.0 standard.

See also: Wink in All Colors.

Update (2015-04-03): Paul Kafasis:

However, after much searching I realized I was to be let down once again. None of the emoji from the updated Unicode 7 spec are included. Apple continues to flip us the figurative bird by refusing to provide us with a literal middle finger. Diversity of races is surely a good thing, but where is the diversity for people who wish to communicate with widely recognized hand gestures? Surely we deserve satisfaction!

Nick Heer:

This is actually — no bullshit — a very good question. Apple tends to be super cautious about being family friendly, to a sometimes ridiculous degree, but the “Reversed Hand With Middle Finger Extended” emoji is a totally valid Unicode character, as much as the letter ‘p’ is. Does Apple’s avoidance of anything even slightly profane trump their full support of the Unicode character set? I don’t think it should. It’s a character, like anything else, and Apple should support it.

Update (2015-04-08): Jason Snell:

The latest betas of OS X and iOS add support for a single new emoji symbol: Raised Hand with Part Between Middle and Ring Finger. […] I assume this is a tribute to Leonard Nimoy, and it’s wonderful. No doubt someone at Apple is dutifully working on all these new emoji symbols, and they’ll eventually debut in a future OS update, but in the meantime, Spock’s salute has gone to a strange, new world: emoji.

Update (2015-04-09): Paul Kafasis:

Unfortunately, however, the much-sought-after “Reversed Hand With Middle Finger Extended” is still unavailable in either of Apple’s OSes. Worse, Apple recently closed the bug report your humble author filed in hopes of making this available to the eager masses!

Hotel Wi-Fi Test

Hotel Wi-Fi Test (via Ilja A. Iwas):

Because your results are bound to the hotel in which you are staying, our speed test is an excellent way to alert them about problems with the service they offer, and motivate them to make changes for the better. You can also offer praise for hotels that go above and beyond and offer great service. During your next hotel stay, visit hotelwifitest.com, take the test, and start sharing so that better hotel WiFi becomes a reality for all of us.

Great idea, although it seems to have no test results for any of the hotels I stayed at in New England and Virginia over the last few years.

Friday, February 6, 2015

Building Swift Bindings to libgit2

Brian Gesiak:

The str parameter is of type UnsafePointer<Int8>, but thanks to Swift’s ability to interoperate with C, we can just pass this function a Swift String. Read the Apple blog article linked above for details.

[…]

Unfortunately, in Interacting with C Pointers in Swift, @develtima explains that we can’t get a usable CFunctionPointer to a function defined in Swift.

So instead, Gift defines Objective-C helper functions that take a Swift closure, and execute that closure from within a C callback function.

Locks, Thread Safety, and Swift

Mike Ash:

Swift requires variables to be initialized before they’re used. pthread_mutex_init doesn’t use the value of the variable passed in, it just overwrites it, but Swift doesn’t know that and so it produces an error. To satisfy the compiler, the variable needs to be initialized with something, but that’s harder than it looks.

[…]

Getting data out of the block is a bit less pleasant, unfortunately. While @synchronized lets you return from within, that doesn’t work with with. Instead, you have to use a var and assign to it within the block[…]

[…]

Swift has no language facilities for thread synchronization, but this deficiency is more than made up for the wealth of locking APIs available in Apple’s frameworks. GCD and dispatch_queue_t are still a masterpiece and the API works great in Swift.

There’s No iOS Backup Feature

John Gordon:

There’s no iOS backup feature.

Yeah, I hear your scoff, but iCloud Backup is not Backup. It’s a system clone. If you delete Contacts accidentally, you can’t readily restore Contacts of, say, 3 days before. When my sister accidentally deleted most of her contacts she had no way to restore them from iCloud.

If she’d been synchronizing with iTunes she could have used a remarkably complicated hack: Recovering iCloud contacts, calendars, and bookmarks from an iTunes backup of an iOS device. Honestly, Apple, that’s just embarrassing.

Awk in 20 Minutes

Fred T-H (via Hacker News):

Awk is a tiny programming language and a command line tool. It’s particularly appropriate for log parsing on servers, mostly because Awk will operate on files, usually structured in lines of human-readable text.

[…]

An Awk script is structured simply, as a sequence of patterns and actions[…]Every line of the document to scan will have to go through each of the patterns, one at a time.

[…]

Finally, the last kind of pattern is a bit hard to classify. It’s halfway between variables and special values, and they’re called Fields, which deserve a section of their own.

Wednesday, February 4, 2015

Overcast Clicker Gestures

Marco Arment:

After months of failing to explain the headphone clicker gestures very well, 1.1.4 finally just shows a picture.

Why the iPad Became My Main Computer

Federico Viticci:

Therefore, three months after I bought an iPad Air 2 and three years into my iPad-as-a-computer experiment, I’d like to offer some thoughts on my current iPad setup and how the device has changed my computing habits.

Because not only do I know what the iPad is good for in my life – the iPad Air 2 finally let me replace my aging MacBook Air as my main computer.

[…]

When I talk about getting work done on my iPad, I don’t mean using companion apps or otherwise having an iPad in addition to a Mac. For the past three years, I’ve been rebuilding the way I run MacStories and co-host two podcasts with an iPad-first workflow in mind. I need to find ways to be productive wherever I am because my life rhythm dictates a constant mobility, but I don’t want to produce subpar work when I’m on an iOS device. I’ve set out to replace the need for OS X in my life, and the combination of iOS 8 and the iPad Air 2 has allowed me to take this effort to the next logical step.

[…]

Apple’s challenge for the next five years of iPad is to clarify whether this device is a portable screen for specific tasks or a general computer in a portable form factor. And if it can excel in both scenarios without losing its way. Apple needs to design the iPad so that its everyday computing nature also facilitates highly specific tasks and use cases.

xed

Seán Labastille reminds us about the xed tool:

The xed tool launches the Xcode application and opens the given documents, or opens a new untitled document, optionally with the contents of standard in.

iOS 9 Wishlist

Clark Goble:

Fix all the bugs and limits in 3rd party keyboards so they work half decent. I want SwipeSelection features without having to jailbreak.

[…]

Fix syncing. I still frequently edit an iWork document and can’t get it to show up on my iOS devices. If you can’t make it work reliably then have an “update iCloud” button to cause it to look for new files. You don’t even need to make it obvious. Just put a button on the iCloud preferences that downloads the latest versions of everything.

[…]

Have groups sync in Contacts/Mail in iOS so I can see groups and mail to groups. I use Groups a lot in OSX. It’s frankly boggling that iOS ignores them for the most part. (If you type a group name in Mail you’ll get listed the members of that group but you have to select them individually from what I can see.)

Tuesday, February 3, 2015

What Color Is Your Function?

Bob Nystrom (via Marco Arment):

But if you have threads (green- or OS-level), you don’t need to do that. You can just suspend the entire thread and hop straight back to the OS or event loop without having to return from all of those functions.

Go is the language that does this most beautifully in my opinion. As soon as you do any IO operation, it just parks that goroutine and resumes any other ones that aren’t blocked on IO.

If you look at the IO operations in the standard library, they seem synchronous. In other words, they just do work and then return a result when they are done. But it’s not that they’re synchronous in the sense that it would mean in JavaScript. Other Go code can run while one of these operations is pending. It’s that Go has eliminated the distinction between synchronous and asynchronous code.

Sunlit and Safari

Manton Reece:

Sunlit 1.3 is a little delayed because it was rejected by Apple for opening Safari to let the user sign in. We’ve appealed the rejection. See also: Craig Hockenberry’s post on why it’s a security risk to use embedded web views.

As far as I can tell, Apple’s store guidelines do not actually document this rule, which is perhaps why Hockenberry referred to it as “Apple’s current App Review policy.”

Update (2015-02-06): Manton Reece:

After a week hanging around in Apple’s Resolution Center, Sunlit 1.3 was approved and went live in the App Store last night.

I’m not sure if I convinced them of anything. :-) But yes, it was approved and went live in the store without further comment. The process is mysterious… I may still change the app later if it’s ever rejected for this again.

Paying to Get Around Adblock Plus

Russell Brandom (via John Gruber):

Some of the web’s biggest companies have been paying to get around Adblock Plus, according to a new report from Financial Times. Microsoft’s Bing search ads and Taboola’s “recommended links” box are among the ads that are currently slipping through Adblock Plus’s filter, and FT confirms that it’s the intentional result of a paid deal between the makers of Adblock and the owners of the ads. According to FT sources, the companies have paid Eyeo (the maker of Adblock Plus) to be added to an official whitelist, which allows them to bypass the plug-in. Google has a similar deal, as has been previously reported.

Monday, February 2, 2015

Neil Young’s PonoPlayer

David Pogue:

The results surprised even me. Whether wearing earbuds or expensive headphones, my test subjects usually thought that the iPhone playback sounded better than the Pono Player.

[…]

The company says it has 2 million songs for sale, but 90 percent of it is in 44.1kHz format — no better than what’s on a CD. The remaining 10 percent, the good stuff, the remastered high-resolution songs, is hard to find.

There’s no way to view only albums available in high resolution. In fact, when you search for a band, a list of its albums appears — but you can’t see what resolution they’re available in until you click a button below the album art. Over and over for each album.

[…]

But maybe you’re different. Maybe you believe that high-res music has more “soul” or is less “tiring” to listen to, as fans claim, even if you can’t actually hear a difference.

In that case, you should note that Pono is not the only high-res player. It has many rivals, like the Astell & Kern AK100 Mk II, iBasso DX50, and the new Sony NWZ-ZX1 Walkman. In fact, Android phones can play the same FLAC-format files, if you get right down to it.

Sam Machkovech:

We took the Pono Player on the go for an entire day, which proved to be a bit of a logistical nightmare. This isn’t just a bad device to put in a pocket—the triangular shape feels noticeable and obnoxious in your pants pocket—but it’s also lousy in a messenger bag. The creators elected not to include a hardware “hold” button of any sort. As a result, the volume and multi-function buttons got pressed on a regular basis during our testing—meaning this thing reached its maximum, incredibly high volume level so quickly that we had to rip earbuds out. We soon opted for handheld use, which was fine enough in terms of quickly adjusting volume, skipping current songs, or pausing. However, we couldn’t disable the screen turning on every time we tapped the volume dial, and turning the screen off required holding the multi-function button down for way too long (so we reduced the auto-sleep timer accordingly).

The best thing we could say about on-the-go Pono use was that the unit fit neatly into our palm and felt like a media-player version of a drum stick. When this thing was cranked to high volume on a good song, we couldn’t help but flick our wrist along and rock out in public.

Cloak and Private Internet Access

Matt Henderson:

The killer feature of Cloak is that it will automatically connect your device—both Mac and iOS—to the VPN whenever you connect to an untrusted wifi network. Furthermore, during that short period of time between connecting to the untrusted wifi network and when the VPN service is enabled, Cloak will block all internet traffic. (How they got all that working in iOS appears to be magic. But it works!)

[…]

So in conclusion, if you connect to public wifi networks, you need to use a VPN service. Cloak provides a great user experience, and just as importantly, is designed to work even when you forget you need it. For most people, it will be the perfect solution. If you travel around enough to run into those rare situations in which Cloak has issues, Private Internet Access is a great backup alternative.

Learn You a Haskell

Miran Lipovača (via Greg Titus):

Hey yo! This is Learn You a Haskell, the funkiest way to learn Haskell, which is the best functional programming language around. You may have heard of it. This guide is meant for people who have programmed already, but have yet to try functional programming.

The whole thing is completely free to read online, but it’s also available in print and I encourage you to buy as many copies as you can afford!

Swift Resistance

David Owens II (Open Radar):

The fundamental problem with Swift, with regards to performance, is that it is impossible to reason what the performance of your code is going to be. It is impossible to know if your code is just horrendously slow in debug, or if the optimizing is going to get ride of all of the extra crap that is going on.

[…]

If most of your code is Swift code that is simply bridging into ObjC or C, you will probably read this post and not have a clue what I’m talking about. You are benefiting from the speed of ObjC.

Profiling showed that a lot of the slowness was from ARC adding unnecessary retains and releases that are only removed when doing an optimized build. Debugging is harder with optimization on, however, and the Swift compiler doesn’t let you selectively disable optimization for a file you are trying to debug.

David Owens II:

Now, had this performance been like 300% slower, I might have been able to take that and the safety justifications… maybe. At least if it was only 300% slower I’d still be in a spot where I could run my game at 30Hz with reasonable head room left over for other logic to run.

But no… we are talking about this loop taking 1 entire SECOND to compute. It was nearly 28,000% slower…

[…]

OK, so let’s be explicitly clear here: this post is not about how Swift is horrendously slow in builds you’ll be giving your customers. No, it’s about how terribly slow and painful your life as a developer will be trying to write any amount of Swift code that works on any reasonable amount of data inside of arrays in Swift. However, you can see that none of the Swift options are faster or even as fast as the C version. And frankly, none of them are really that much clearer… but that’s a different topic.

Joseph Lord:

Where I would dispute with David is his view that this is an absolute showstopper than cripple’s Swift’s usefulness. There are ways to manage without the debugger, it still works with the assembly if needed anyway and as I illustrate there are workarounds for the issue.

However in the repo I show the workaround of moving performance critical code to a library or framework that can be built optimised while the bulk of the complexity and logic in the project is run without optimisation for simplicity of debugging.

David Owens II:

The other problem with this statement (and the solution presented) is that it assumes that we can optimize the slow parts of the game by putting the code into a framework. Ok… besides the annoying mess that is to pull stuff in and out of there, and completely ignoring that this is a trivial example of one algorithm that would need to be moved, it completely misses the fact that it’s that very slow part that I need to debug because something strange is going on. If my debug build is now running at 2 or 3 Hz, it becomes extremely difficult (impossible really) to actually play to game to get the error that is to be debugged.

ZPedro:

I do take back what I said yesterday somewhat, to the extent that:

(Apple bug 1) not only do per-file flags seem to be completely ignored altogether on Swift source files (I tried with -toto, it did not appear in the command line while building), contrary to what I implied yesterday,

(Apple bug 2) but also Swift code does not appear to be supported at the moment in static library targets (it failed when I tried and I found reports that appear to confirm this),

(Apple bug 3) and framework targets containing Swift code do not play well with command line tool targets,

I am forced to reach the conclusion that, since you can’t reasonably put it in a separate area where it can be optimized differently (and be accessed by command-line targets, which is essential for specifically testing that code instead of having to do it through an app), Swift is unsuitable for multimedia code at the time being (Mac OS X Yosemite and Xcode 6.1.1, if you’re an Apple engineer reading…). Period.

GHRunLoopWatchdog

Justin Spahr-Summers’s GHRunLoopWatchdog is a class forlogging excessive blocking on the main thread (via iOS Dev Weekly).

Why Can’t Twitter Fix Their Mac App?

Matt Henderson:

When Twitter announced dropping support for third-party developers and clients, the stated justification was that Twitter wanted ensure that every user received the best Twitter experience possible, and that could only be achieved if Twitter themselves controlled all vehicles through which users experienced the platform.

Fine, but how can we reconcile that position with the awful state of Twitter for Mac today, and the fact that it is apparently receiving zero attention within the company?

React Native

Facebook’s Tom Occhino introduces React Native (via Ole Begemann, comments).

Josh Abernathy:

React Native is not a write-once-run-everywhere solution. The phrase Facebook has used so far is “learn-once-write-everywhere.” They’re interested in sharing the paradigm of React across platforms, not the code necessarily.

[…]

React let us describe our entire UI for a given state, and then it does the hard work of figuring out what needs to change. It abstracts all the fragile, error-prone code out away from us. We describe what we want, React figures out how to accomplish it.

UIs become composable, immutable, stateless value types.

Andy Matuschak:

I say with confidence as a former UIKit author: React’s model for the UI layer is vastly better than UIKit’s. React Native is a huge deal.

People asked why I like React’s model over UIKit’s: it does a better job of promoting isolation and confining effects, while being simpler.

Jordan Walke (via Nick Lockwood):

This is not the DOM. This is not a web view. If you know ReactJS, you can build native apps with React Native.

How to Mount a Disk on Startup

Ovidiu Predescu:

MacOS X Yosemite removed few capabilities that existed in previous versions of MacOS X. Notably the StartupItems feature which allowed you to run scripts when the system boots up.

On my machine I want to be able to mount an internal disk as soon as the machine boots up, but before a user logs in. A common solution in the past involved a custom StartupItems script, but this no longer works on Yosemite.

He shows how to do this with a launchd file in the LaunchDaemons folder.

Hydra Camera App

Creaceed (App Store):

Thanks to innovative capture technology, Hydra lets you take beautiful pictures even in the most difficult lighting conditions. That makes it a great companion to the built-in Camera app on your iPhone or iPad.

How does it work? Hydra merges up to 60 individual images to make a single high-quality picture, effectively getting more light from the scene. That way, Hydra produces up to 32-megapixel high-resolution images (4x the 8-megapixel sensor resolution), enhanced HDR, better 2x/4x zoom, and reduced camera noise in low-light scenes.

Sounds promising for photographing static subjects.

Prefer Composition to Inheritance

Soroush Khanlou:

But this is inelegant and we wish we could just force our users to subclass something so that we can hide this behavior away. But don’t fret! We have options outside of inheritance. To add behavior in a composition-friendly way, we use the Decorator pattern.

[…]

A particularly elegant note on this solution: the wrapper itself doesn’t conform to SKRequestTemplate, even though its parameter does. This means that if we add a new method to the protocol and try to use it from the safe template, the compiler will groan at us. It must be defined on the safe template before we can use it, and we’ll be reminded to add it there as well. Normally, with inheritance, your “contract” with the outside world includes all of your superclass’s methods; with decoration, you only have to provide what you say you’ll provide. Aaron Patterson documents a case where the rails/core team got bitten by this exact problem.

Sunday, February 1, 2015

Phantom Types and Typed Notification Observers

objc.io:

Using these types, we can create two more wrappers, but this time around NSFileHandle’s initializers. We’ll use the Read and Write types, even though the FileHandle doesn’t contain any values of that type. That’s why the A parameter is called a phantom type. The types are just there to track permissions.

[…]

Trying to call this function on a file-handle that’s open for writing will not even compile. You can use these techniques for important parts of your own code as well, if you have areas where you want the compiler to check errors for you, rather than having the code fail at runtime.

objc.io:

Finally, we can create our observer object. Creating an instance of this object adds an observer to NSNotificationCenter, and when it deallocs, it removes itself from the notification center. This allows us to store it as a property on an object, and once the property gets set to nil (e.g. when the object deallocs), it automatically removes itself from the notification center.

Then they use phantom types to make sure that a given notification is always posted with the proper type of user info object.

The IOU of iOS

Chris Ashworth:

If some app developers “earn more than Hollywood stars”, and the median developer income is better than abject poverty… that doesn’t tell us that the App industry is healthy so much as at least slightly less insane than working as an actor. Which, and I say this as an actor, is true of, well, basically any other job. So, not much to learn there.

[…]

The sense I sometimes get with iOS is of work done in exchange for a vague IOU. A belief in the obvious technical and design merits of the platform, an acknowledgement of the unprecedented rates of adoption for these devices, and perhaps an excitement watching the stars strike gold. A culture thick with the pervasive mantra “mobile first”, which might make all the sense in the world to one kind of business endeavor, but may make no sense at all for other kinds of toolmakers.

Apple is not, I would say, directly (or consciously) responsible for promising something that iOS can’t deliver. But neither are they entirely neutral. They design the mechanics of the App Store. They design and construct how apps are discovered.

[…]

The 30% cut Apple takes really is huge. It also, I think, encourages us to build apps that are free. And if the apps are free, they’re in service to something else that isn’t free. Some software-as-a-service, or a product sold through another channel which can be made more attractive with a mobile extension. This gentle pressure to push the actual value outside of iOS strikes me as problematic, long-term.

Swift & the Objective-C Runtime

Nate Cook:

Unfortunately, a load class method implemented in Swift is never called by the runtime, rendering that recommendation an impossibility. Instead, we’re left to pick among second-choice options:

  • Implement method swizzling in initialize
    This can be done safely, so long as you check the type at execution time and wrap the swizzling in dispatch_once (which you should be doing anyway).

  • Implement method swizzling in the app delegate

Dynamic Casting in Swift

Samuel E. Giddins:

We can even define some syntactic sugar on top of this type verification:

func id<U>(object: AnyObject) -> U? {
  if let typed = object as? U {
    return typed
  }
  return nil
}

[…]

OK, that last example might not look like a huge improvement, but coupled with Swift’s powerful type inference, you can 'magically’ type objects at runtime with a single function call.

You have to call the id() function, but depending on the context Swift may be able to infer the types.

1Password 5.2 for iOS and 5.1 for Mac

Agile Bits:

For our Pro feature owners, let’s start with a new One-Time Password tool. This helps you sign into a growing number of services (like Amazon and Tumblr) that support a secondary, randomized password for that extra… je ne sais quoi. You can learn more about One-Time Passwords at TwoFactorAuth.org.

It’s nice to not have to rely on Google Authenticator for two-factor authentication. Plus, 1Password’s data is easier to back up and sync. Google Authenticator has the advantage of larger digits that (in recent versions) are separated into two groups with a hyphen. Given that my QR code images are already stored in 1Password, you would think there would be a way to import them directly, but it was easy enough to aim the phone’s camera at 1Password on my Mac.

Agile Bits:

In short, we completely overhauled how you manage sync for your primary and secondary vaults to save you time. In Preferences > Sync, you can now view all your vaults and how they sync, and change sync methods with a click.

This is much nicer, although you still cannot edit the color or icon for a secondary vault after creating it.

Weakness

Edge Cases discusses weak references and how entries in Andrew Pontious’s hash table don’t get cleared away promptly. Surprisingly, Apple’s doesn’t do better.

Categorical

Soroush Khanlou:

-[NSString containsString:] was added in iOS 8. If you’re writing a standard library, this seems like one of the most crucial components for string handling. And yet, it’s been conspicuously absent since the early ’90s, when NSString was created.

[…]

So given these myriad reasons why categories aren’t good enough, why will Apple not implement these methods?

[…]

Other vendors have proven that it’s possible to do this well. Ruby, for example, takes it to the other extreme: their Integer objects respond to methods like #odd?, #even? and even #gcd. Providing those methods in the standard library yields more readable code and it gives the vendor the opportunity to tweak and optimize them at later date, knowing that anyone who needs them will benefit from their optimizations.

[…]

In the same way that base types like Swift’s Optional or JavaScript ES6’s Promises must be built-in for proper adoption, these simple methods need to be available to all developers. Apple’s proclivity towards leaving holes in their API forces developers into a bind. We must either write inexpressive, hard-to-read code, do needless work opening these classes back up, or leave a trail of dependencies in our wake.

YouTube Now Defaults to HTML5 Video

Richard Leider (via John Gruber):

Four years ago, we wrote about YouTube’s early support for the HTML5 <video> tag and how it performed compared to Flash. At the time, there were limitations that held it back from becoming our preferred platform for video delivery. Most critically, HTML5 lacked support for Adaptive Bitrate (ABR) that lets us show you more videos with less buffering.

Over the last four years, we’ve worked with browser vendors and the broader community to close those gaps, and now, YouTube uses HTML5 <video> by default in Chrome, IE 11, Safari 8 and in beta versions of Firefox.

Web video is getting better, but the situation remains difficult with older Macs. My grandmother’s Mac mini can’t run anything later than Snow Leopard. She is constantly running into problems with YouTube because her Flash Player is too old. It seems unable to update itself automatically. I wanted to set her up with Chrome, which has its own Flash and its own auto-updater. It works on 10.6 but only if you have a 64-bit Mac. Meanwhile, YouTube wants Safari 8, but Snow Leopard can only run Safari 5.

Who Else Kinda Misses Their Zip Disks?

Christopher Phin:

A little over 20 years ago, however, when Iomega introduced the original 100MB Zip disk, that was staggeringly huge for a removable disk. The wildly more common 3.5-inch floppies held 1.4MB. For context, the entry-level PowerBook 150, introduced in the same year, had a 120MB hard disk, and the base configurations of even 1994’s server Macs came with hard disks that were only five times the capacity of the Zip disk.

The humble Zip disk, then, was a kind of de facto successor to the ubiquitous high-density 3.5-inch floppy. You had to buy a special drive to mount it in, because although they had about the same footprint as a regular floppy disk, they were much thicker. In fact, Zip disks had a lovely chunky, seemingly hugely robust quality compared to normal floppies.

As I recall, the novelty wasn’t that the Zip disk was huge in capacity. In that respect, it was similar to the SyQuest and Bernoulli removable disks of the day. What was special was that Zip disks were physically smaller and much cheaper. And, in spite of the “click of death,” I recall them being more reliable than their 88 MB SyQuest predecessors and their 1 GB Jaz successors.

Some Notes on Rust, the Language

John Nagle:

Despite the claims in the Rust pre-alpha announcement of language definition stability, the language changes enough every week or so to break existing programs. This is a classic Mozilla problem; that organization has a track record of deprecating old features in Firefox before the replacement new feature works properly.

[…]

Rust is going to be a very important language, because it solves the three big problems of C/C++ that causes crashes and buffer overflows. The three big problems in C/C++ memory management are “How big is it?”, “Who owns and deletes it?”, and “Who locks it?”. C/C++ deals with none of those problems effectively. Rust deals with all of them, without introducing garbage collection or extensive run-time processing. This is a significant advance.

Protocols and Swift

Ash Furrow:

Here’s the problem I ran into: in a pure Swift environment, I want to have optional methods in my protocol so that objects that conform to it may opt-in to certain functi onality. It turns out that this is really really hard.

[…]

I’m not saying that this is necessarily how I would actually write things – it’s only supposed to show you how dividing areas of concern into separate protocols makes things a lot more clear.

[…]

Sure, you’ll probably have only one object that conforms to all the protocols you need (and be honest – it’s probably a view controller, isn’t it?). But the power of this technique is not that we can divide the various data sources into different objects. Instead, the advantage is that we don’t have additional semantic coupling between functions in the protocol. Of course canMoveRowAtIndexPath can only be called if moveRowAtIndexPath is also implemented – they’re in the same protocol.

Update (2015-02-02): David Owens II:

It’s just another way of thinking about the problem. Swift seems to be a language that values immutability and composition over mutability and if we start to think about solving problems that way, I think we end up with more solutions like I presented where it’s really just about how we manipulate the data in composable ways.