Latest 1.0.1
License MIT
Platforms ios 8.0

This library provides an extension on NSObject that allows the use of key value coding without fear of exceptions.


Key value coding is a bit of Cocoa magic that remains unique to ObjC through NSObject. However, NSObject’s KVO methods throw exceptions when things go south and these cannot be caught in Swift. The category this library provides wraps NSObject’s KVO methods in @try/@catch blocks and when an exception is thrown an NSError object is populated instead.


Usage is simple. First import:

import SGYKVCSafeNSObject

Then use key value coding as before by optionally passing NSError:

let object = NSObject()
var error: NSError?
object.setValue("any value", forKey: "not a key", error:&error)
if let error = error { NSLog("Key value assignment error: (error.localizedDescription).") }

Known Issues

  • When using valueForKey: or valueForKeyPath: the exception is not returned in a userInfo dictionary. During testing attempting to pass the caught NSException in these methods seems to randomly cause an EXC_BAD_ACCESS. So to maintain safety the exception object is not packed into a userInfo dictionary until I can nail down the reason.

Latest podspec

    "name": "SGYKVCSafeNSObject",
    "version": "1.0.1",
    "summary": "A category on NSObject that converts key value coding exceptions to NSError objects.",
    "description": "Provides a safe way to use key value coding on NSObject.  Since Swift does not support ObjC's @try command it cannot catch the exceptions thrown using key value coding (eg. setValue:forKey).  This library provides an extension on NSObject that will catch these exceptions and report them via NSError so that they can be safely used in Swift.",
    "homepage": "",
    "license": "MIT",
    "authors": {
        "Sean G Young": "[email protected]"
    "source": {
        "git": "",
        "tag": "1.0.1"
    "platforms": {
        "ios": "8.0"
    "source_files": "SGYKVCSafeNSObject/Classes/**/*"

Pin It on Pinterest

Share This