• Stars
    star
    398
  • Rank 108,325 (Top 3 %)
  • Language
    Objective-C
  • License
    MIT License
  • Created over 12 years ago
  • Updated 10 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Objective-C Key-Value Observing made easier with blocks

Block Observing

Overview

Key-Value Observing made easier with blocks.

This is an extension to Key-Value Observation mechanism and allows you to use blocks as observation handlers. Block Observing can be used and mixed with classic KVO without any problems.

You should be familiar with the concepts of Key-Value Observing and Key-Value Coding.

Library and example app in this project are for iOS, but you can use in OS X project too by importing the source files directly.

Integration

  1. Drag the project into your project (as a child or sibling).
  2. Add Block Observing to Target Dependencies in Build Phases.
  3. Add libBlockObserving.a to Link Binary With Libraries in Build Phases.
  4. Add -ObjC and -all_load as Other Linker Flags in Build Settings.
  5. Make sure you have Header Search Paths in Build Settings set up (e.g. Libraries/**).
  6. Import MTKObserving.h to your files (usually in Prefix.pch).

CocoaPods central repositary will no longer be updated. Use this: pod 'Block-KVO', :git => 'https://github.com/Tricertops/Block-KVO.git'

Features

Observe using block

Any object can observe its own key-path using block handler. Caller and receiver must be the same object and the key-path must be relative to the receiver.

[self observeProperty:@keypath(self.profile.username) withBlock:
 ^(__weak typeof(self) self, NSString *oldUsername, NSString *newUsername) {
     self.usernameLabel.text = newUsername;
 }];

Block arguments has no specific type (so they are id). You are supposed to specifiy the type by yourself as you want. Primitive values are wrapped by NSNumber or NSValue instances

Quick macros

The above code example using provided macro:

MTKObservePropertySelf(profile.username, NSString *, {
    self.usernameLabel.text = new;
});

Equality check

IMPORTANT: This is different from the standard KVO.

Once the value of observed property changes, but the values are equal (using -isEqual: method) the observation blocks are not invoked. For example self.title = self.title; will not trigger observation.

No retain cycles inside the blocks

All observation blocks have first argument the receive/caller with name self. It overrides method argument self, but contains the same object. The only difference is __weak attribute. In the example code above, you can use self and will not cause retain cycle.

Observe Using Selector

If you want to get out of the current scope, you can just provide selector instead of block.

[self observeProperty:@keypath(self.profile.username) withSelector:@selector(didChangeUsernameFrom:to:)];

Observe more key-paths at once

There are methods that take an array of key-paths and one block (or selector).

One-way binding (mapping)

Map property to another property. Once the source key-path changes, destination is updated with the new value. Transform the value as you wish.

[self map:@keypath(self.profile.isLogged) to:@keypath(self.isLoggedLabel.text) transform:
 ^NSString *(NSNumber *isLogged) {
     return (isLogged.boolValue ? @"Logged In" : @"Not Logged In");
 }];

Also, there is convenience method for specifying replacement for null value.

[self map:@keypath(self.profile.username) to:@(self.usernameLabel.text) null:@"Unknown"];

Two-way binding (mapping)

Two-way binding can be achieved by using two one-way bindings. Don't worry about recursion, because observation is supressed if the values are equal.

[self map:@keypath(self.task.isDone) to:@keypath(self.doneButton.selected) null:nil];
[self map:@keypath(self.doneButton.selected) to:@keypath(self.task.isDone) null:nil];

Observe NSNotifications using blocks

Improved observation of notifications using blocks. NSNotificationCenter provides some support for this, but here you don't need to worry about removing those blocks or retain cycles.

Remove Observations

Removing is now automatic.


The MIT License
Copyright Β© 2012 – 2016 Martin Kiss

More Repositories

1

KeepLayout

Making Auto Layout easier to code.
Objective-C
836
star
2

Objective-Chain

Object-oriented reactive framework, inspired by ReactiveCocoa
Objective-C
237
star
3

UIView-AnimatedProperty

Extending `UIView` block animations to allow you to implement custom animated properties.
Objective-C
158
star
4

Grand-Object-Dispatch

Objective-C wrapper for Grand Central Dispatch
Objective-C
101
star
5

Typed

Brings type inference to Objective-C with almost no hacks.
Objective-C
86
star
6

ITNDescription

Automatic and smart -debugDescription for every Objective-C class.
Objective-C
33
star
7

GrandSwiftDispatch

Not so Grand, not so Swift, and not so Dispatch
Swift
28
star
8

Valid-KeyPath

Allows you to specify Objective-C key-paths using symbols taking all advantages – code-completion, complite-time validation, refactoring.
Objective-C
25
star
9

Essentials

Collection of categories, functions, macros and classes that are essential part of my projects.
Objective-C
18
star
10

MTKButtonState

Allows you to set UIButton state-based properties with dot syntax.
Objective-C
17
star
11

NSObject-GCD

NSObject+GCD: Category on NSObject with methods that wrap some of the GCD functions.
Objective-C
12
star
12

TetrisEngine

Core of a simple Tetris game with no UI
Swift
12
star
13

Where

Locate the user of the current iOS device without CoreLocation.
Objective-C
10
star
14

Yield

Support for multiple entry points and return values in Objective-C.
Objective-C
7
star
15

GEOCoordinateFormatter

NSFormatter for geographic coordinates
Swift
6
star
16

jDateFormat

Never again write date formats by hand. YYYY anyone?
C
4
star
17

LinearKit

Objective-C wrapper for Accelerate framework.
Objective-C
4
star
18

SwiftToolbox

Collection of additions to Swift that I use in every project.
Swift
4
star
19

Adoption

OS X Today Widget to show iOS 9 adoption.
Swift
4
star
20

JSONArchiver

NSCoder that produces JSON object archives, replacement for NSKeyedArchiver.
Objective-C
3
star
21

RichArchiver

Archivation tool for `NSAttributedStrings` for cross-platform exchange – OS X to iOS
Objective-C
3
star
22

CSVBuilder

Swift class that builds CSV files from provided cell data.
Swift
2
star
23

iOS-Toolbox

Open-source app with a collection of tools for iOS devs.
Objective-C
2
star
24

YAML

Attempt to use YAML conveniently from Swift and Objective-C.
Swift
2
star
25

MTKResource

Dealing with iOS devices, screen sizes, languages and extensions.
Objective-C
1
star
26

Objective-R

Not a language.
1
star
27

Geocoder

Geocoding app quickly built with Swift as a tool to inspect address formats around the world.
Swift
1
star
28

Fractioning

Convert decimal numbers to fractions.
Objective-C
1
star
29

SQL-Model

Objective-C modeling library that generates SQL statements.
Objective-C
1
star
30

TRITableModel

Collections modeled to be suitable as UITableView data source.
Objective-C
1
star