Thoughts, stories and ideas.

Dispatch Sources: Timer

Dispatch souces define an event source that when triggered can invoke a pre-defined callback. Instead of registering for events and then writing logic to handle events to make a callback, dispatch source can be used.

Dispatch timer

For example, with interval timers, its not trivial to setup NSTimer outside of main threads as it requires a run-loop with predictable lifetime. Using a runloop outside main thread is painful. Dispatch queues have ephimeral threads and as such are bad candidates for use with NSTimers.

This is a scenario where dispatch source is an ideal use-case. A dispatch timer source, fires an event when the time interval has been completed, which then fires a pre-set callback all on the same queue.

// Define a queue
queue = dispatch_queue_create("com.blah",0);
// Define timer
interval_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
// Configure timer with type(wallclock), interval(2 mins), leeway(5)
// leeway is acceptable error
dispatch_source_set_timer( interval_timer, dispatch_walltime(NULL,0), 2*60, 5 );
// Callback when timer is fired
dispatch_source_set_event_handler(interval_timer, ^{
	NSLog(@"Timer event");

It is also easy to start and suspend timer events. Its as simple as calling

dispatch_resume( interval_timer );
dispatch_suspend( interval_timer );

Dispatch After

If an event needs to be fired after a time interval, but does not require cancellation, it is simpler to just use dispatch_after

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(<delayInSeconds> * NSEC_PER_SEC)), <queue>, ^{
    // code to be executed after a specified delay

Example: Flushing Queue after time interval

Here is some pseudo/sample code that consumes objects via -addEvent: until - either the object count becomes <N>, or <T> seconds have elapsed since last object add and in the end calls -flush:

@implementation KCTimer
	dispatch_source_t _interval_timer;
	dispatch_queue_t _flush_queue;
	NSUInteger _count;
	NSUInteger _timelimit;

- (instancetype) initWithCount:(NSUInteger)count andTimeLimit:(NSUInteger)limit 
	if( self = [super init] ) {
		_timelimit = limit;
		_count = count;

		_flush_queue = dispatch_queue_create("com.blah",0);
		_interval_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, flush_queue);
		dispatch_source_set_event_handler(_interval_timer, ^{
			[self flush];
		[self reset];
		[self resume];
	return self;

- (void)resume
	dispatch_resume( _interval_timer );

- (void)suspend
	dispatch_suspend( _interval_timer );

- (void)reset
	dispatch_source_set_timer( interval_timer, dispatch_walltime(NULL,0), _timelimit, 5 );

- (void)addEvent:(Event *)e 
	// TODO: Add stuff in thread safe manner
	[self reset];
	if(eventCount >= 50) {
			[self flush];

- (void)flush
	// TODO: Flush queue in thread safe manner

Go-lang Notes


Sometimes its hard to believe that this is indeed a compiled language, mostly due to type inference.
In most cases you do not need to specify type in declarative initialization unless you are just declaring.

var someInt int; // type required
anotherInt := 23 // type not required

Type inference is only available inside functions and not in top level declarations. The designers state that it is by design to optimise for faster compilation.

Arrays & Maps

Coming from python and objective-c, I always took for granted that I can dump in any type of object into either an array or a dictionary/map; This is not something you can do in Go and I initially presumed this might become an obstacle. I was surprised to note that I felt no need for it at all, yet.

The syntax seemed complicated initiaially, but its its quite simple if you know how go synatax goes

// Declaring
var Mapping map[string]string;
Mapping = make(map[string]string)

// string maps to string
var Dictionary := make(map[string]string)

// String maps to *Route
var RouteMapping := make(map[string]*Route)


Everything outside the realm of simple functions almost always involves types. They have to be used for

  1. structs (for oop-ish things)

     type TinyServer struct {}
  2. aliases a.k.a typedefs

     type TinyConnectionHandler func(*TinyConnection)
  3. interfaces

     type TinyServerHandler interface {}


Golang is not particularly object oriented. It is possible to achieve the notion of it using structs, associated methods and composition.

Composition Example:

type Connection struct {
	ResponseWriter http.ResponseWriter
	Request  *http.Request

type TinyConnection struct {
	Url *url.URL
	Vars map[string]string

This makes all methods as well as variables from Connection available in TinyConnection struct. Trying to override a method will cause a compile time error.

Associated Methods:

func (connection *Connection) WriteString(content string) {
	fmt.Fprintf(connection.ResponseWriter, content)

At first look the syntax may look quite odd especially if you are coming from other languages like python. But I found it to be quite similar to C++, with the exception of position of return which in Go is at the end.

void Connection::WriteString(char *string){


Another oddity of golang is how interfaces are implemented - You declare an interface and its contents, but you never explicitly specify if a struct/class implements an interface. Consider this example:

type Handler interface {
    ServeHTTP(ResponseWriter, *Request)

type MyHandler struct {}
func (MyHandler *h) ServeHTTP(ResponseWriter, *Request) {}

The struct MyHandler is assumed to implement the interface Handler just because it implements ServeHTTP method. It almost feels like its duck typing, although attempting to assign handler directly will cause compile error.

type Server struct {
	handler Handler

myHandler := &MyHandler{}
server := &Server{}
server.handler = myHandler // compiler error

The only way to do the above assignment is to create a new instance of the interface and assign the pointer value

handler := new(Handler)
*handler = myHandler
server.handler = *handler


An amusing aspects of the regexp module is that the method naming conforms to a regex. Straight from godoc:

There are 16 methods of Regexp that match a regular expression and identify the matched text. Their names are matched by this regular expression:


Multiple returns

functions can return multiple values. This although is part of the language, its not very different from returning a tuple in python

def returnTwoThings():
	return (1,2)	
a, _ = returnTwoThings()


func returnTwoThings() (int,int) {
	return (1,2)
a, _ := returnTwoThings()

Only major difference is in go, the return types have to be explicitly declared. This means one can't arbitrarily decide to return 3 items unlike python.


Go does not compile to a binary executable unless there is a main package and there exists a main() function.

Garbage Collection

The language is designed to be garbage collected. So the binary ships with a GC. Although this is great if the final main() is in go, its not useful if you'd like to use your go code to work with something written and compiled C.

In short: You can import C code into Go. The vice versa is not possible, yet.
There goes my dream of building a mac/ios app in golang.

Detect touches on words in UILabels

Detecting touches on UIViews is quite trivial. But trying to recognize touches on individual words or attributed strings can be not so much, which was exactly what I wanted to do.

There are 2 approaches one can take

  • CoreText and compute the frames of all glyphs
  • TextKit - which is not exactly kit per se, but are bunch of classes part of UIKit


TextKit is designed based on MVC, with:

  • M being NSTextStorage
  • V being NSTextContainer
  • C being NSLayoutManager

NSTextStorage acts as the data provider and can own multiple NSLayoutManagers. For the layout manager to display text, it needs an instance of NSTextContainer, which essentially defines the area of visible text.

NSTextContainer has 2 main properties defining the layout - the bounds and the exclusion paths. Bounds is the outline rect, this is required. Optionally one can pass a bezier path to define which areas are not to be layouted - allowing one flow text around images.

Here is some code that detects touch on "Read More" string of a UILabel*.


	Some initialization
- (void)viewDidLoad {
	// The full string
	NSMutableDictionary *attributesForString = [[NSMutableDictionary alloc] init];
	attributesForString[ NSFontAttributeName ] = [UIFont systemFontOfSize:13];
	self.attrString = [[NSMutableAttributedString alloc] initWithString:@"Lorem ipsum dolor set amit"];
	// The "Read More" string that should be touchable
	attributesForString[ NSFontAttributeName ] = [UIFont boldSystemFontOfSize:13];
	self.moreString = [[NSAttributedString alloc] initWithString:@"READ MORE" attributes:attributesForString];
	[self.attrString appendAttributedString:self.moreString];
	// Store range of chars we want to detect touches for
	self.moreStringRange = [self.attrString.string rangeOfString:self.moreString.string];
	self.textLabel.attributedString = self.attrString;

	UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self selector:@selector(didTap:)];
	[self.textLabel addGestureRecgonizer:tapRecognizer];

	Simple touch recognition.
	Could be setup during initialisation.
- (void)didTap:(UITapGestureRecognizer *)gesture {
	// Storage class stores the string, obviously
	NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:self.attrString];
	// The storage class owns a layout manager
	NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
	[textStorage addLayoutManager:layoutManager];
	// Layout manager owns a container which basically
	// defines the bounds the text should be contained in
	NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:self.textLabel.frame.size];
	// For labels the fragment padding should be 0
	textContainer.lineFragmentPadding = 0;
	// Begin computation of actual frame
	// Glyph is the final display representation
	// Eg: Ligatures have 2 characters but only 1 glyph.
	NSRange glyphRange;
	// Extract the glyph range
	[layoutManager characterRangeForGlyphRange:self.moreStringRange actualGlyphRange:&glyphRange];
	// Compute the rect of glyph in the text container
	CGRect glyphRect = [layoutManager boundingRectForGlyphRange:glyphRange inTextContainer:textContainer];
	// Final rect relative to the textLabel.
	NSLog( @"%@", glyphRect );
	// Now figure out if the touch point is inside our rect
	CGPoint touchPoint = [gesture locationOfTouch:0 inView:self.textLabel];
	if( CGRectContainsPoint(glyphRect, touchPoint) ) {
		NSLog( @"User tapped on Read More. So show something more");

Sketch Plugin to resize iOS app icon to all resolutions

Most common use-case of designing an iOS App Icon, simply involves designing the main [email protected] and then resizing it to all other resolutions. Since the default template does not come with a smart symbol available across all artboards, you have to create one and copy it over and resize it manually.

Since I am too lazy to do it, I wrote a sketch plugin in javascript.


  1. Open Sketch
    • Create New From Template
    • iOS App Icon
  2. Design in [email protected] Artboard
  3. Make sure all design happens inside one single layer group in the art board.
  4. Open Plugins menu option and select Custom Plugin
  5. Copy Paste code from below
  6. Run & Profit!


var resizeToAllCanvases = function(context) {

	// Current board
	var artboards = context.document.artboards();
	var mainBoard;

	for( i=0; i<artboards.count(); i++) {
		if( artboards[i].name().containsString("iTunesArtwork") )
			mainBoard = artboards[i];

	var mainShape = mainBoard.layers().firstObject();
	var mainName= mainBoard.name();

	// Go through all the art boards
	// and copy the layer group
	for( i=0; i<artboards.count(); i++) {
		if( artboards[i].name() != mainBoard.name() )  {
			var targetBoard = artboards[i]

			// Resize
			mainRect = mainShape.rect()
			mainSize = mainRect.size;
			newRect = CGRectZero;
			newRect.size = targetBoard.rect().size;
			newSize = newRect.size;
			// Copy the Layer item
			mainShapeCopy = mainShape.copy()
			mainShapeCopy.frame().width = newSize.width;
			mainShapeCopy.frame().height = newSize.height;

			// Clear out the art board and paste layer
			targetBoard.layers().addObject( mainShapeCopy )


Convert DXF to SVG

After discovering a local makerspace which has free open days, I wanted to try their laser cutter, for which I needed to provide a file in SVG format.

One of the challenges I set myself up for was to be able to create model and have series of scripts to do the rest of conversion for me.

I started with a simple sliced model in OpenSCAD, which unfortunately only exported to DXF format

module side() {
	difference() {
		cube([50, 50, 10], center = true);
		translate([-10,0,0]) cube([20, 20, 10], center = true);

projection(cut=true) side();

So I first converted to DXF

$ ~/Applications/OpenSCAD/Contents/MacOS/OpenSCAD -o ex1.dxf ex1.scad 

There are no tools out there to ease the conversion to SVG (on mac at least). Inkscape does support it, but getting it to run on Mac was a hassle. So I resorted to using FreeCAD which has nice python bindings, to write an export script

# exporter.py 
import sys
ifile = sys.argv[0]
ofile = sys.argv[1]

import importDXF
import importSVG

obj = importDXF.open( ifile )
importSVG.export( obj.Objects, ofile )

And then converted the DXF to SVG using this

$ ~/Applications/FreeCAD.app/Contents/bin/FreeCADCmd exporter.py ex1.dxf ex1.svg

Here is the final result