— boreal-kiss.net

As an overview, the book covers significantly a wide range of topic from 3D drawing to peripheral libraries (videos, audios, OpenCV, etc.) as well as topics that are new to Processing 2.0 (Processing.js and mobile programming) that I have not seen described on other books before. I find this is very new; open source communities prefer webs to keep resources up to date. This is also the case for Processing. Since paper materials could get easily out of date in these restless fields, publishers tends to avoid such a risk. As a result lots of topics concerning Processing have not been covered on paper books yet. However, I always prefer getting information from a paper book to through webs. I would like to highly rate this book in terms of the fact that more than a half of the book’s content is first introduced on a paper material.

Throughout the book, I feel this book is a collection of tutorials rather than a cookbook. Each chapter describes one large theme which is divided into small consecutive recipes that are written in the step-by-step way. This is very helpful to a novice who knows nothing about it; everything will work by just following the book. However, since every small step is monotonously described no matter how important it is, it is hard to find the core of a subject even in the second time of reading.

Each chapter describes an introduction part of its theme and no advanced part. In fact a recipe has the “There’s more” section, where the author directs advanced users to resources beyond the book. It is so introductive that one easily understands on a single reading and won’t need to read it again. In my opinion a cookbook must be one dealing with topics that are hard to keep in mind or must be one with whom one could work more easily and more efficiently. This is a major reason why I won’t call the book cookbook. If the book were more tailored to daily usage (like a dictionary), described more deeply, or had more advanced topics, the book would be more valuable.

In the end, the book is not a collection of techniques and/or algorithms for drawing aesthetics. If you are the one who seeks for such a subject, this book is not for you. If you want to grab what could be done with Processing and to know how to do it, this book would be a good starting point.

Processing 2: Creative Programming Cookbook

Read More

In the first two sections I will give you brief reviews on Processing related IDEs (Processing IDE and Eclipse). In the third section, I will introduce Sublime Text 2 and the way how to integrate with Processing drawing API. If you urge to know how to do it, go to the third section.

1. Problems on Processing IDE

Processing is an easy-to-use, lightweight drawing tool that comes with really sophisticated libraries written in Java. It’s so easy that one could launch the application and write some code to embody the idea in his mind within a few minutes. It’s like drawing a daily sketch on a paper and the result will be amazingly beautiful thanks to its great libraries. I love it as an artist.

However I, as a developer, have found some problems on Processing IDE. First, I have been always annoyed by its strange indentation like the picture below; each time I push the enter key, indentation occurs differently even in the same lexical scope. This gives me an additional work to fix them, is really time-consuming, is not relavant with drawing at all.

Second, Processing IDE wont’ well manage a project when it gets larger with a bunch of class files. This mainly comes from the combination of the nature of the Processing framework and the IDE:

  • Processing uses Java inner classes. All class files must resides within the same hierarchy with a main project file.
  • The IDE automatically includes all the class files within the project. Each class always shows up in tab panes.

You can easily imagine the catastrophe when you work with, let’s say a project with one hundred class files. All class files will immediately show up in tab panes. Nobody would like to tab-browse all of them at the same time but Processing IDE offers you. The picture below is an example of my projects which has 20 class files. I will not see which tab is which even after expanding the window to the monitor size. I only know the class name after selecting one of the tabs.

2. Eclipse as a nice alternative but…

The problems above could be solved when one goes to Eclipse. It’s an IDE tailoring to Java development. Since the Processing framework is also written in Java, one could also make a Processing project on Eclipse (For the detail see the tutorial: Processing in Eclipse). The Eclipse IDE won’t give you any strange indentation nor a nightmare of managing a large project. Each class file is properly managed and/or protected by Java’s namespace so that one can easily spot what he wants to see. Changing class files’ hierarchy in a project scale is even a piece of cake thanks to the refactoring function. Really nice, at least for developers. For artists no; the IDE is super heavy. It’s so heavy to launch that one must wait a minute or more watching the opening pane (you will be soon bored by seeing the picture below) before actual drawing. Since the waiting time will easily kills one’s idea in the head, Eclipse is not suitable to a daily sketch.

3. Sublime Text 2 as a nice alternative, yes!

Having used Sublime Text 2 for a while, I find it meeting my needs both as an artist and developer:

  • It’s well developed as an editor. No annoying bugs for me so far (e.g., strange indentation behaviour etc.).
  • It’s lightweight and launches fast.
  • It well manages any size of a Java project (less effective than Eclipse IDE though), so it is suited to Processing drawing as well.

My current way of Processing drawing on Sublime Text 2 follows these steps:

  1. Write everything in Java, linking the Processing drawing API framework (core.jar). This enables the Java project to use Processing API.
  2. Compile and run the Java program with javac- and java-command line tool.

Since using Sublime Text 2 for Processing drawing needs some additional works awful to command line beginners (me also), I will explain them step by step.

3-1. Link to Processing API

Right-clicking the Processing.app to show package contents, you can find a file called “core.jar” (Java archive file) in the following path:

/Applications/Processing.app/Contents/Resources/Java/core/library/core.jar

Processing’s PApplet class (main class for Processing) is defined in this file. Extending the main class of a Java project to the subclass of PApplet, one could use Processing standard drawing API (you will see the actual linkage to this file when compiling in the next section). The Java Main class (bare-bone) looks like the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//Main.java
 
import processing.core.PApplet;
 
public class Main extends PApplet{
	public static void main(String args[]) {
		PApplet.main(new String[] {Main.class.getName()});
	}
 
	//Processing setup method.
	public void setup(){
 
	}
 
	//Processing draw method.
	public void draw(){
 
	}
}

We will run a program from this class as an entry point.

3-2. Customize Sublime Text 2 settings

Since Sublime Text 2 simply compile the Java program and won’t run the program by the built-in Build command, we need customize its settings. Browsing packages (Sublime Text 2 > Preferences > Browse Packages…), find Java build setting file named “JavaC.sublime-build” (you should better backup this file in case) :

~/Library/Application Support/Sublime Text 2/Packages/Java/JavaC.sublime-build

(“~” means my home directory) The default looks like the following, showing that it only compiles a Java file with javac command line tool:

//Original JavaC.sublime-build.
 
{
	"cmd": ["javac", "$file"],
	"file_regex": "^(...*?):([0-9]*):?([0-9]*)",
	"selector": "source.java"
}

Since compiling and running a Java project from command line needs multiple instructions for better use (e.g., create a bin directory to separate binary files from source for house keeping, etc.), we direct Sublime Text 2 to execute a bash file (I’ll call it “java_compile.sh”) that contains some necessary instructions, rather than execute javac command directly. My customized “JavaC.sublime-build” is the following (the path to the bash file is not important):

//Customized JavaC.sublime-build.
 
{
	"cmd": ["~/Documents/Java/java_compile/java_compile.sh", "$file"],
	"file_regex": "^(...*?):([0-9]*):?([0-9]*)",
	"selector": "source.java"
}

Inside the bash file, I added the following commands:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#!/bin/bash
#java_compile.sh

#Path to a directory for storing class files.
PATH_TO_BIN_DIR="../bin"
 
#Create the directory above if not exists.
mkdir -p $PATH_TO_BIN_DIR
 
#Remove all binary files created at the previous compile time.
find $PATH_TO_BIN_DIR -type f -name "*.class" -exec rm -f {} \;
 
#Strip the path component.
file_name=$(basename $1)
 
#Strip the file extension.
class_name="${file_name%.*}"
 
#Path to the Processing core library.
PATH_TO_JAR_FILE="/Applications/Processing.app/Contents/Resources/Java/core/library/core.jar"
 
#Compile.
javac -d $PATH_TO_BIN_DIR -classpath $PATH_TO_JAR_FILE: $file_name
 
#Run.
java -classpath $PATH_TO_BIN_DIR:$PATH_TO_JAR_FILE: $class_name

When building Main.java by Build command on Sublime Text 2, this bash file will be executed, linking to the Processing library, compiling all the files to store them in a bin directory in the parent directory, and running the program. Below is an example of a project hierarchy.

Make sure the bash file is executable. In Terminal.app, type the following command from the same directory where the bash file is:

chmod u+x java_compile.sh

For more tuning around java command line tools, read the related article: How to Compile and Run Java Code from a Command Line.

Edited at 24.11.2012

One of readers gave me a comment that he had difficulties with the compile when linking multiple external libraries. Since I also find this is very hard for people who is not familiar with shell scripting, I’ll show you the way how to do this; basically what you have to do is concatenate files’ path string into one variable that will be an argument for classpath option both in compile- and run- time. As an example here is my compile file when I use OpenGL libraries (Processing 2.0). Hope this would save your time.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#!/bin/bash
#java_compile.sh

#Path to a directory for storing class files.
PATH_TO_BIN_DIR="../bin"
 
#Create the directory above if not exists.
mkdir -p $PATH_TO_BIN_DIR
 
#Remove all binary files created at the previous compile time.
find $PATH_TO_BIN_DIR -type f -name "*.class" -exec rm -f {} \;
 
#Strip the path component.
file_name=$(basename $1)
 
#Strip the file extension.
class_name="${file_name%.*}"
 
#Core: path to the Processing core library.
PATH_TO_JAR_FILES="/Applications/Processing.app/Contents/Resources/Java/core/library/core.jar"
 
#Optional: path to OpenGL libraries.
PATH_TO_JAR_FILES=$PATH_TO_JAR_FILES:"/Applications/Processing.app/Contents/Resources/Java/core/library/jogl-all.jar"
PATH_TO_JAR_FILES=$PATH_TO_JAR_FILES:"/Applications/Processing.app/Contents/Resources/Java/core/library/gluegen-rt.jar"
 
#Compile.
javac -d $PATH_TO_BIN_DIR -classpath $PATH_TO_JAR_FILES: $file_name
 
#Run in 32-/64-bit mode.
#java -d32 -classpath $PATH_TO_BIN_DIR:$PATH_TO_JAR_FILES: $class_name
java -d64 -classpath $PATH_TO_BIN_DIR:$PATH_TO_JAR_FILES: $class_name
Read More

As a pygame exercise, I wrote a scalable Nyan Cat animation from scratch, i.e., everything from Python code.

Example

The simplest implementation is here. To run animation you have to take the following three steps:

  1. Create objects (cat, rainbow, and stars)
  2. Draw the objects
  3. Update the objects’ state.

Note that half of the code is boilerplate for pygame. You of course need pygame to run the code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
	import pygame
	from nyancat import Nyancat
	from rainbow import Rainbow
	from star_manager import StarManager
 
	pygame.init()
	DISPLAY_SURFACE = pygame.display.set_mode((320, 240))
	BACKGROUND_COLOR = pygame.Color(15, 77, 143)
	DISPLAY_SURFACE.fill(BACKGROUND_COLOR)
	FPS = 12
	CLOCK = pygame.time.Clock()
 
	#Create objects.
	cat = Nyancat(pygame.Rect(110, 90, 100, 250))
	rainbow = Rainbow(cat.rect, cat.pixelSize)
	stars = StarManager(DISPLAY_SURFACE.get_rect(), cat.pixelSize, 10)
 
	while True:
		DISPLAY_SURFACE.fill(BACKGROUND_COLOR)
 
		for e in pygame.event.get():
			if e.type == pygame.QUIT:
				pygame.quit()
				sys.exit()
 
		#Draw the objects. 
		rainbow.draw(DISPLAY_SURFACE)
		cat.draw(DISPLAY_SURFACE)
		stars.draw(DISPLAY_SURFACE)
 
		#Update the animation state of the objects.
		rainbow.update()
		cat.update()
		stars.update()
 
		pygame.display.update()
		CLOCK.tick(FPS)

Download

You can download the source from https://github.com/borealkiss/nyancat.py.

Read More

JoystickController is an Arduino library that is fully compatible with SparkFun’s Joystick Shield. The library lets you easily fetch the current status of the joystick. Implementation is quite simple;

  JoystickController(int low = DEFAULT_LOW, int high = DEFAULT_HIGH)

is a constructor. The first argument specifies the lower threshold value for the directional key pad, below which the controller is assumed to set left/down in the horizontal/vertical direction. The second argument specifies the upper threshold value, above which the controller is assumed to set right/up in the horizontal/vertical direction. If arguments are not specified, the following default values will be used:

  static const int DEFAULT_LOW  = 490;
  static const int DEFAULT_HIGH  = 530;

(Note these variables are defined as private so that you can not directly access them) For more information about the threshold see the following article: How do I find the current direction of the joystick?

 void update()

must get called in the main loop in order for the library to communicate with the joystick.

  int getDirection()

returns the current direction of the directional keypad as integer values that are defined as class static variables:

  static const int DIRECTION_NONE = 0;
  static const int DIRECTION_UP = 1;
  static const int DIRECTION_UP_RIGHT = 2;
  static const int DIRECTION_RIGHT = 3;
  static const int DIRECTION_DOWN_RIGHT = 4;
  static const int DIRECTION_DOWN = 5;
  static const int DIRECTION_DOWN_LEFT = 6;
  static const int DIRECTION_LEFT = 7;
  static const int DIRECTION_UP_LEFT = 8;

Finally buttons’ status can be fetched from the following functions:

  bool upButtonPressed()
  bool downButtonPressed()
  bool leftButtonPressed()
  bool rightButtonPressed()
  bool selectButtonPressed()

They return true if a button is being pressed, otherwise false. 

Example

Here is a simple example for the library implementation.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include "JoystickController.h"
 
JoystickController controller;
 
void setup(){
  Serial.begin(9600);
}
 
void loop(){
  controller.update();
 
  if (controller.selectButtonPressed()){
    Serial.println("S"); 
  }
 
  if (controller.upButtonPressed()){
    Serial.println("U"); 
  }
 
  if (controller.downButtonPressed()){
    Serial.println("D"); 
  }
 
  if (controller.leftButtonPressed()){
    Serial.println("L"); 
  }
 
  if (controller.rightButtonPressed()){
    Serial.println("R"); 
  }
 
  int direct = controller.getDirection();
 
  switch (direct){
    case  JoystickController::DIRECTION_UP:
      Serial.println("UP");
      break;
    case  JoystickController::DIRECTION_UP_RIGHT:
      Serial.println("UP-RIGHT");
      break;
    case  JoystickController::DIRECTION_RIGHT:
      Serial.println("RIGHT");
      break;
    case  JoystickController::DIRECTION_DOWN_RIGHT:
      Serial.println("DOWN-RIGHT");
      break;
    case  JoystickController::DIRECTION_DOWN:
      Serial.println("DOWN");
      break;
    case  JoystickController::DIRECTION_DOWN_LEFT:
      Serial.println("DOWN-LEFT");
      break;
    case  JoystickController::DIRECTION_LEFT:
      Serial.println("LEFT");
      break;
    case  JoystickController::DIRECTION_UP_LEFT:
      Serial.println("UP-LEFT");
      break;
  }
 
  delay(100);
}

Download

The library is available from my Github repository: JoystickController

Read More

I used a potentiometer as a joystick controlling the graphics on the computer. For demonstration purposes, I’ll show partial source code used in the above application (communication part only).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
//Arduino
 
int _out = 0;
float _vMax = 5.0;
 
void setup(){
  Serial.begin(9600);
}
 
void loop(){
  float v = 5.0 * analogRead(_out) / 1023.0;
  sendMessage(v);
  delay(100);
}
 
void sendMessage(float input){
  float dv = _vMax / 5;
 
  if (input < 1 * dv){
    Serial.print("D");
  }
  else if (input < 2 * dv){
    Serial.print("R");
  }
  else if (input < 3 * dv){
    Serial.print("U");
  }
  else if (input < 4 * dv){
    Serial.print("L");
  }
  else{
    Serial.print("D");
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
//Processing
 
import processing.serial.Serial;
 
Serial _port;
 
void setup(){
  //Setup drawing. 
}
 
void draw(){
  this.receiveMessage();
  //Update drawing.
}
 
void receiveMessage(){
  if (_port == null){
    _port = new Serial(this, Serial.list()[0], 9600);
  }
 
  if (_port.available() > 0){
    String message = _port.readString();
 
  if (message.equals("U")){
    //UP
  }
 
  if (message.equals("D")){
    //DOWN
  }
 
  if (message.equals("L")){  
    //LEFT
  }
 
  if (message.equals("R")){
    //RIGHT
  }
}
Read More

A company logo of Aperture Science drawn on Processing. Aperture Science is a virtual company appearing in a video game Portal.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
void setup(){
  size(640, 640);
  background(255);
  fill(0);
  noStroke();
  smooth();
  noLoop();
}
 
void draw(){
  this.drawLogo();
}
 
void drawLogo(){
  final float RAD = 0.5 * width;
 
  //Inner radius.
  float r0 = 0.6 * RAD;
 
  //Outer radius.
  float r1 = 0.9 * RAD;
 
  //Octagon.
  final int NUM_VERTEX = 8;
 
  //Lateral angle for each shape.
  float dAngle = 2.0 * PI / (float)NUM_VERTEX;
 
  //Margin between shapes.
  float mAngle = 2.0 * PI / 180.0;
 
  final float CENTER_X = 0.5 * width;
  final float CENTER_Y = 0.5 * height;
 
  for (int i=0; i<NUM_VERTEX; i++){
    beginShape();
 
    //Add an inner vertex.
    float t0 = (i + 1) * dAngle;
    float x0 = CENTER_X + r0 * cos(t0);
    float y0 = CENTER_Y + r0 * sin(t0);
    vertex(x0, y0);
 
    //Add vertices for an arc.
    float t1 = (i - 0.5) * dAngle + mAngle;
    float t2 = (i + 0.5) * dAngle - mAngle;
    this.addVerticesForArc(CENTER_X, CENTER_Y, r1, t1, t2);
 
    endShape(CLOSE);
  }
}
 
//Add vertices for an arc. Must be used between beginShape() and endShape().
void addVerticesForArc(float centerX, float centerY, float rad, 
                                                     float startAngle, float endAngle){
  final int NUM_VERTEX = 100;
  float dt = (endAngle - startAngle) / (float)NUM_VERTEX;
 
  for (int i=0; i<NUM_VERTEX; i++){
    float x = centerX + rad * cos(startAngle + i * dt); 
    float y = centerY + rad * sin(startAngle + i * dt);
 
    //Add vertices.
    vertex(x, y);
  }
}
Read More

One of my drawings became the cover art of Simian Mobile Disco‘s new album, Unpatterns, with which you will experience impressive Moiré patterns both on CD and vinyl. The shape of the drawing is inspired by Bridget Riley‘s Riley Waves.

There is also an associated iPhone app, where you can listen to their full album with interactive contents same as my Moiré app plus exclusive shapes. This is also a part of the collaboration.

Available on the App Store

Read More

Minimal Template for iOS 5

Minimal Template for iOS 5 part2

My project template for iOS working on Xcode 4 has been updated. I use a storyboard file (iOS 5 and later) rather than xib. Since all the source code including the content of the storyboard is not hard-coded in the template, You can easily modify their contents without having a catastrophe (adding/removing files needs some efforts though). If you are not familiar with storybords, the following guide will be helpful:

You can find the complete template at my repository:

Read More

In order to make an application universal one has to detect the device’s idiom (iPhone/iPad) at run time. This is easily done with the following conditional:

if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
	//iPad specific codes.
}
else{
	//iPhone specific codes.
}

You might have used this conditional, for example, when you want to control a view’s rotation or a modal view’s behavior depending on the current device’s idiom. The above conditional is simple and easy to implement when the application is simple. However once the application has lots of behaviors varying on the device’s idiom here and there, your source codes will get messy and hard to read and/or maintain, due to the duplication of this snippet spreading over your project.

Fortunately this will be easily resolved by using the well known State pattern. As the name suggests, State pattern deals with the internal state of its participating context and does some work without unnecessarily exposing other states that the context could have. As describing such patterns only in words is always hard to figure out, I’ll give you an example to walk through with.

Example

Consider the following situation. You want to control a view’s rotation depending on the device’s idiom:

  • On iPhone, the application allows one of portrait modes (Home button at the bottom).
  • On iPad, the application allows both portrait and landscape modes.

The implementation for this in a straightforward way looks like this:

-(BOOL)shouldAutorotateToInterfaceOrientation:
					(UIInterfaceOrientation)interfaceOrientation{
 
	if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
		//iPad.
		return YES;
	}
	else{
		//iPhone.
		if (orientation == UIInterfaceOrientationPortrait){
			return YES;
		}
		return NO;
	}
}

In this example, I’ll add some tweaks for the above snippet to look cleaner. That is:

  1. Wrap the codes inside the conditional into a block object.
  2. Register them in a dictionary object.
  3. Retrieve the block object from the dictionary when needed.
  4. Invoke the block.

1-2. Create blocks and register them in dictionaries

The key trick here is wrapping into blocks will done for iPhone and iPad separately:

//For iPhone.
BOOL (^blockiPhone)(UIInterfaceOrientation orientation) = 
						^(UIInterfaceOrientation orientation){
	if (orientation == UIInterfaceOrientationPortrait){
		return YES;
	}
	return NO;
};
 
[_dictionaryForiPhone setObject:[[blockiPhone copy] autorelease] 
						forKey:@"viewRotation"];
//For iPad.
BOOL (^blockiPad)(UIInterfaceOrientation orientation) = 
						^(UIInterfaceOrientation orientation){
	return YES;
};
 
[_dictionaryForiPad setObject:[[blockiPad copy] autorelease] 
						forKey:"viewRotation"];

Here the dictionary objects as a registry assume to be instance variables in the class.

NSMutableDictionary *_dictionaryForiPhone;
NSMutableDictionary *_dictionaryForiPad;

Note that although the value of the key string here is arbitrary, you would better give a meaningful name for its later usage. Also note that since block objects are yet in the stack, they must be copied to the heap before adding to the collections.

3. Retrieve blocks

Then I provide a method retrieving a appropriate block object corresponding to the device’s idiom:

//Incomplete.
-(id)blockForKey:(NSString *)key{
	if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
		return [_dictionaryForiPad objectForKey:key];
	}
	else{
		return [_dictionaryForiPhone objectForKey:key];
	}
}

This is redundant since the conditional inside the method gets evaluated each time the method gets called. So add I additional tweaks. These look like this;

//Complete
-(id)blockForKey:(NSString *)key{
	if (!_idiomDetected){
		if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
			_dictionaryForCurrentIdiom = _dictionaryForiPad;
		}
		else{
			_dictionaryForCurrentIdiom = _dictionaryForiPhone;
		}
		_idiomDetected = YES;
	}
 
	return [_dictionaryForCurrentIdiom objectForKey:key];
}

Here two new instance variables are introduced:

BOOL _idiomDetected;
NSDictionary *_dictionaryForCurrentIdiom;

The boolean value is used for testing whether the application already detected the device’s idiom or not. If detected the application skips the conditional. If not, the application tries to detect the current device’s idiom and assign the reference to the appropriate block dictionary to _dictionaryForCurrentIdiom. Doing this, block objects will be retrieved only from this referencing dictionary, hiding the fact that there are actually two different collections of blocks (iPhone/iPad), thanks to State pattern.

4. Invoke blocks

Finally the above method will get called in the right place:

-(BOOL)shouldAutorotateToInterfaceOrientation:
					(UIInterfaceOrientation)interfaceOrientation{
	BOOL (^block)(UIInterfaceOrientation) = [self blockForKey:@"viewRotation"];
	return block(interfaceOrientation);
}

Note that in order to invoke a block correctly one must know the type of the block properly (Since you are the adder of blocks, you must know well their types, right?).

Now my codes are free from conditional, looking very tidy. Although the example here is trivial, this pattern will give you its real strength when the application has more and more device specific behavior (controlling modal views, if iPhone 4S, if iPad 2, and so on).

BKUIIdiomController

If you want to try this but save your time, here is my idiom controller class. The class only has two APIs:

-(void)setBlockForiPhone:(id)blockForiPhone 
				blockForiPad:(id)blockForiPad forKey:(NSString *)key;
-(id)blockForKey:(NSString *)key;

The first method for registering blocks (one for iPhone, the other for iPad) associated with a given key string. The second is for retrieving an appropriate block for the current device’s idiom. You could easily understand how to use this if you read this article. The demo project with full source codes are below:

Read More

Why subclassing? Because I’m bored by preparing a bare-bone singleton from scratch.

+[NSObject initialize] is invoked only once in a thread-safe manner before a class object receives any message (for more detail see NSObject Class Reference). Therefore this method could be a good place for a singleton instance to be created.

Here is my singleton class. I won’t show the complete implementation here. To be robust you should control methods concerning allocation such as alloc, init, copy, etc. However these are not of importance here. To check these visit the following site:

//BKSingleton.h
 
#import <Foundation/Foundation.h>
 
@interface BKSingleton : NSObject{
 
}
 
/**
 * Returns a singleton instance.
 */
+(id)sharedInstance;
 
@end
//BKSingleton.m
 
#import "BKSingleton.h"
 
static NSMutableDictionary *_dictionary = nil;
 
@implementation BKSingleton
 
+(id)sharedInstance{
	NSString *className = NSStringFromClass(self);
	return [_dictionary objectForKey:className];
}
 
+(void)initialize{
	if (!_dictionary){
		_dictionary = [[NSMutableDictionary dictionary] retain];
	}
 
	NSString *className = NSStringFromClass(self);
 
	if (![_dictionary objectForKey:className]){
		[_dictionary setObject:[[[self alloc] init] autorelease] forKey:className];
	}
}
 
@end

When a subclass of this class is first received a message, the initialize method of this class is invoked (i.e., +[BKSingleton initialize]) unless this is overridden in the subclass.

The first trick here is that there is no hard-coded class names inside the initialize method (e.g., something like [MyClass alloc]). Thanks to this even the subclass is received its superclass’s initialize method, it is always instantiated by the correct class.

The second trick is that the instance of a subclass is stored in a static class dictionary associated with its class name if there is not such an object with the same key found in the dictionary. Doing this ensures that the dictionary holds a unique instance for each subclass.

Let’s see an example. There are two subclasses inherited from BKSingleton. They have nothing newly implemented.

//Singleton1
 
#import "BKSingleton.h"
 
@interface Singleton1 : BKSingleton{
 
}
 
@end
 
@implementation Singleton1
 
@end
//Singleton2
 
#import "BKSingleton.h"
 
@interface Singleton2 : BKSingleton{
 
}
 
@end
 
@implementation Singleton2
 
@end

Then run the following code.

//main.m
 
#import <Foundation/Foundation.h>
#import "BKSingleton.h"
#import "Singleton1.h"
#import "Singleton2.h"
 
int main(int argc, char *argv[]) {
	NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
 
	NSLog(@"BKSingleton: %@", [BKSingleton sharedInstance]);
	NSLog(@"Singleton1: %@", [Singleton1 sharedInstance]);
	NSLog(@"Singleton2: %@", [Singleton2 sharedInstance]);
 
	//Once again
	NSLog(@"BKSingleton: %@", [BKSingleton sharedInstance]);
	NSLog(@"Singleton1: %@", [Singleton1 sharedInstance]);
	NSLog(@"Singleton2: %@", [Singleton2 sharedInstance]);
 
	[pool release];
	return 0;
}

The output is the following, ensuring they are al unique, i.e., singletons.

Test[1153:207] BKSingleton: <BKSingleton: 0xe0a880>
Test[1153:207] Singleton1: <Singleton1: 0xe08d20>
Test[1153:207] Singleton2: <Singleton2: 0xe0b620>
Test[1153:207] BKSingleton: <BKSingleton: 0xe0a880>
Test[1153:207] Singleton1: <Singleton1: 0xe08d20>
Test[1153:207] Singleton2: <Singleton2: 0xe0b620>

Related links

Read More