2013年11月13日水曜日

Objective-C でシングルトンパターン (緩め)

Objective-C でシングルトンを実現するのは、ちゃんとやろうとすると、結構手間です。例えば、ARC (Automatic Reference Counting) 無効の場合、次のブログが示しているように、シングルトンインスタンスを取得するメソッドを追加するだけでは話は終わらず、あまり直感的ではない方法で複数のメソッドをオーバーライドしなければなりません。

Objective-C でシングルトンパターン
http://blog.syuhari.jp/archives/2178

ARC 有効となると、書き方も変わってきます。

言語の特性上、呼び出し側で無茶なことができてしまうケースが幾つかあるので、シングルトン実装側だけで完全性を達成しようとするのは難しいと思います。そのため、ある程度シングルトン的な構造にはしておくものの、呼び出し側がひねくれたことをやったら責任は負えないよ、という実装で落ち着くというのも、ケースによっては許容できると思います。

なので、例えば次のようなシングルトンの実装もありではないでしょうか。

// シングルトンインスタンスを保持する変数。
// static を付けているので、C 言語の仕様上、
// 他のソースコードからは参照できない。
static MyClass *_instance;

// +(void)initialize は Objective-C にとって特別。
// クラスの初期化時に一度だけ呼ばれる。
+ (void)initialize
{
    // あるクラスが initialize メソッドを実装していない場合、
    // そのスーパークラスの initialize メソッドが呼ばれて
    // しまうそうなので、同期をとっておく。(今回のケースでは
    // シングルトンクラスのサブクラスを作るというような変な
    // ことでもしない限り、当 initialize メソッドが複数回
    // 呼ばれることは無いが、一般的なコード例として同期)
    @synchronized (self)
    {
        // まだシングルトンインスタンスが作成されていなければ
        if (_instance == nil)
        {
            // シングルトンインスタンスを作る。初期化メソッドは
            // init ではなくて initInternal としておく。
            _instance = [[MyClass alloc] initInternal];
        }
    }
}

// シングルトンインスタンスを取得するためのクラスメソッド。
// sharedInstance というメソッド名はよく使われるので、
// その慣習に従うことにする。
+ (MyClass *)sharedInstance
{
    return _instance;
}

// デフォルトの初期化メソッド。間違って呼ばれないよう、
// 機能しないように実装しておく。
- (id)init
{
    // 呼び出し側が間違えて init メソッドを呼ぶことのないよう、
    // つまり _instance 以外のインスタンスを作ることがないよう、
    // init メソッドは機能しないようにしておく。ここでは、
    // 「そんなメソッド知らない」という例外を投げることにする。
    [self doesNotRecognizeSelector:_cmd];

    return nil;
}

// init のかわりの初期化メソッド。Objective-C の言語仕様上、
// 外部から initInternal を呼ぶことはできてしまうが、わざわざ
// 公開もしていない initInternal を呼んでシングルトンパターンを
// 壊すことをするようなら、それは呼び出し側が悪いので、何が
// 起こっても知ったことではない。
- (id)initInternal
{
    self = [super init];

    return self;
}

// 以下はヘッダファイル内の記述。init メソッドは使用できないと
// 宣言しておく。
- (id)init UNAVAILABLE_ATTRIBUTE;

2013年11月12日火曜日

Android Test プロジェクトを実行すると NoClassDefFoundError

Eclipse で Android プロジェクトを「ライブラリ」としてマークすると、project.properties というファイルに android.library=true と書かれるが、この状態で、このプロジェクトをターゲットプロジェクトとする Android Test プロジェクトを作って Android JUnit Test を実行すると、NoClassDefFoundError が出てしまう。この問題を回避するためには、ターゲットプロジェクトの android.library=true を消すか android.library=false にするかしないといけない。

android.library=true のままだと、{ターゲットプロジェクト}.apk がインストールされないため、{ターゲットプロジェクト}.apk 内のクラスがことごとく見つからない状態 (NoClassDefFoundError) になってしまうらしい。

なんか釈然としないけど、テストプロジェクトが動いたからいいや。

The accepted answer for "Android Eclipse - Could not find *.apk".
http://stackoverflow.com/a/6450971

2013年11月5日火曜日

Getting Started With Ruby/DBI + Oracle on Mac

1. Download Oracle Instant Client from the download page.

  • instantclient-basic-macos.x64-11.2.0.3.0.zip
  • instantclient-sdk-macros.x64-11.2.0.3.0.zip

2. Unzip the zip files.

$ cd /usr/local
$ unzip instantclient-basic-macro.x64-11.2.0.3.0.zip
$ unzip instantclient-sdk-macros.x64-11.2.0.3.0.zip

3. Create a symbolic link to the libclntsh library.

$ cd instantclient_11_2
$ ln -s libclntsh.dylib.11.1 libclntsh.dylib

4. Prepare a configuration file for Oracle clients.

$ vi /etc/tnsnames.ora

your-service-name =
  (DESCRIPTION =
    (ADDRESS =
      (PROTOCOL = TCP)
      (HOST = your-host-name)
      (PORT = 1521)
    )
    (CONNECT_DATA =
      (SERVICE_NAME = your-service-name)
    )
  )

5. Set up some environment variables.

$ export DYLD_LIBRARY_PATH=/usr/local/instantclient_11_2
$ export NLS_LANG=Japanese_Japan.AL32UTF8
$ export TNS_ADMIN=/etc/

6. Install DBI and the driver for Oracle.

$ gem install dbi
$ gem install ruby-oci8

7. Write a test script.

$ vi test.rb

#!/usr/bin/env ruby

require 'rubygems'
require 'dbi'

user = 'your-user-name'
password = 'your-password'
service_name = 'your-service-name'


DBI.connect("DBI:OCI8:#{service_name}", user, password) do |dbh|
  row = dbh.select_one("SELECT * FROM v$version")
  puts "Server version = #{row[0]}"
end

8. Run the test script and it'll show a result like below.

Server version = Oracle Database 11g Release 11.2.0.1.0 - 64bit Production

2013年10月11日金曜日

From Installing Xcode To Running Fluentd On Mac

  1. Install Xcode    [download]
  2. Install Command Line Developer Tools
    Xcode: [Preferences] -> [Downloads] -> [Command Line Tools]
  3. Install MacPorts    [installation guide]
  4. Install RVM (Ruby Version Manager)    [installation guide]
    $ \curl -L https://get.rvm.io | bash -s stable --ruby
    
  5. Apply RVM's configuration
    $ . ~/.bash_profile
    
    $ which rvm
    /Users/takahiko/.rvm/bin/rvm
    
  6. Install Ruby 2.0    [ruby homepage]
    # 2.0.0-p247 is the latest version on Oct 11, 2013.
    $ sudo rvm install ruby-2.0.0-p247
    
    $ which ruby
    /Users/takahiko/.rvm/rubies/ruby-2.0.0-p247/bin/ruby
    
    $ ruby --version
    ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-darwin12.3.0]
    
  7. Update gem
    $ which gem
    /Users/takahiko/.rvm/rubies/ruby-2.0.0-p247/bin/gem
    
    $ gem update --system
    
  8. Install fluentd    [fluentd homepage]
    $ gem install fluentd
    
    $ which fluentd
    /Users/takahiko/.rvm/gems/ruby-2.0.0-p247/bin/fluentd
    
  9. Setup fluentd
    $ fluentd --setup ./fluentd
    
  10. Run fluentd
    $ fluentd -c ./fluentd/fluent.conf
    
  11. Send a log message to fluentd
    $ curl http://localhost:8888/debug.http -F \
      'json={"greeting":"hello"}'
    # You'll see some output in fluentd's console.
    

2013年9月20日金曜日

Arial Black on Firefox

Firefox has a bug due to which Arial Black is not treated correctly. A workaround is to add "font-weight: 900;", but an answer at StackOverflow seems better.

Firefox には「Arial Blackフォントが効かない」という不具合があり、それを回避するために、「font-weight: 900;」を加える、という方法があるそうだが、StackOverflow にあった回答のほうがスマート。

@font-face {
  font-family: 'arial-black';
  src: local('Arial Black');
}

#nav {
  font-family: "Arial Black", arial-black, sans-serif;
}

2013年4月11日木曜日

Message digests (MD5, SHA1, etc.) on iOS with dedicated classes

Project nv-ios-digest (Apache License, Version 2.0) provides Objective-C classes that are dedicated to computation of message digests such as MD5 and SHA-1. An example code below prints MD5 hash value of "Hello, world.".

// Create an MD5 instance using the convenience constructor.
MD5 *md5 = [MD5 md5WithString:@"Hello, world."];

// Print the MD5 hash value as string.
// This will show "md5 = 080aef839b95facf73ec599375e92d47".
NSLog(@"md5 = %@", md5);


Another example code below shows another different way to compute MD5 with update and final.

// Create MD5 instance for computation.
md5 = [[MD5 alloc] init];

// Update. See also
// updateWith:(const void *)data length:(CC_LONG)length
[md5 updateWithString:@"Hello, world."];

// Final. The returned pointer points to the internal buffer
// of md5 whose size is CC_MD5_DIGEST_LENGTH (=16).
unsigned char *md = [md5 final];

// After 'final', a valid NSString expression is available
// through 'description' method.
NSLog(@"md5 = %@", md5);


Supported algorithms are as follows.

  • MD5
  • SHA1
  • SHA224
  • SHA256
  • SHA384
  • SHA512

A simple implementation to add md5 method to NSString will look like the following.

// NSString+MessageDigest.h
#import <Foundation/Foundation.h>
#import "MD5.h"
@interface NSString (MessageDigest)
- (MD5 *)md5;
@end

// NSString+MessageDigest.m
#import "NSString+MessageDigest.h"
@implementation NSString (MessageDigest)
- (MD5 *)md5
{
    return [MD5 md5WithString:self];
}
@end

And its usage will be:

#import "NSString+MessageDigest.h"

NSLog(@"md5 = %@", @"Hello, world.".md5);


Project Page
https://github.com/TakahikoKawasaki/nv-ios-digest


2013年4月3日水曜日

Get and compare iOS version at runtime with Version class

With Version class that is contained in nv-ios-version project (Apache License, Version 2.0), it is easy to get and compare iOS version. An example code below dumps the iOS version and check whether the version is greater than or equal to 6.0.

// Get the system version of iOS at runtime.
NSString *versionString = [[UIDevice currentDevice] systemVersion];

// Convert the version string to a Version instance.
Version *version = [Version versionWithString:versionString];

// Dump the major, minor and micro version numbers.
NSLog(@"version = [%d, %d, %d]",
    version.major, version.minor, version.micro);

// Check whether the version is greater than or equal to 6.0.
if ([version isGreaterThanOrEqualToMajor:6 minor:0])
{
    // The iOS version is greater than or equal to 6.0.
}

// Another way to check whether iOS version is
// greater than or equal to 6.0
if (6 <= version.major)
{
    // The iOS version is greater than or equal to 6.0.
}

In Version API, the valid range of major, minor and micro is between 0 and 255. If an invalid value is given, NSInvalidArgumentException is thrown. The default values of major, minor and micro are 0.

number in the API is "(major << 16) | (minor << 8) | micro".

description method returns "major.minor" when micro is 0. Otherwise, "major.minor.micro". For example, "6.1" is returned for version 6.1.0, and "6.1.1" for version 6.1.1.

Version class provides many comparison methods.

#pragma mark -
#pragma mark Comparison
- (NSComparisonResult)compareToMajor:(int)major;
- (NSComparisonResult)compareToMajor:(int)major minor:(int)minor;
- (NSComparisonResult)compareToMajor:(int)major minor:(int)minor micro:(int)micro;
- (NSComparisonResult)compareToNumber:(int)number;
- (NSComparisonResult)compareTo:(Version *)aVersion;

#pragma mark -
#pragma mark Comparison (equal to)
- (BOOL)isEqualToMajor:(int)major;
- (BOOL)isEqualToMajor:(int)major minor:(int)minor;
- (BOOL)isEqualToMajor:(int)major minor:(int)minor micro:(int)micro;
- (BOOL)isEqualToNumber:(int)number;
- (BOOL)isEqualTo:(Version *)aVersion;

#pragma mark -
#pragma mark Comparison (not equal to)
- (BOOL)isNotEqualToMajor:(int)major;
- (BOOL)isNotEqualToMajor:(int)major minor:(int)minor;
- (BOOL)isNotEqualToMajor:(int)major minor:(int)minor micro:(int)micro;
- (BOOL)isNotEqualToNumber:(int)number;
- (BOOL)isNotEqualTo:(Version *)aVersion;

#pragma mark -
#pragma mark Comparison (less than)
- (BOOL)isLessThanMajor:(int)major;
- (BOOL)isLessThanMajor:(int)major minor:(int)minor;
- (BOOL)isLessThanMajor:(int)major minor:(int)minor micro:(int)micro;
- (BOOL)isLessThanNumber:(int)number;
- (BOOL)isLessThan:(Version *)aVersion;

#pragma mark -
#pragma mark Comparison (less than or equal to)
- (BOOL)isLessThanOrEqualToMajor:(int)major;
- (BOOL)isLessThanOrEqualToMajor:(int)major minor:(int)minor;
- (BOOL)isLessThanOrEqualToMajor:(int)major minor:(int)minor micro:(int)micro;
- (BOOL)isLessThanOrEqualToNumber:(int)number;
- (BOOL)isLessThanOrEqualTo:(Version *)aVersion;

#pragma mark -
#pragma mark Comparison (greater than)
- (BOOL)isGreaterThanMajor:(int)major;
- (BOOL)isGreaterThanMajor:(int)major minor:(int)minor;
- (BOOL)isGreaterThanMajor:(int)major minor:(int)minor micro:(int)micro;
- (BOOL)isGreaterThanNumber:(int)number;
- (BOOL)isGreaterThan:(Version *)aVersion;

#pragma mark -
#pragma mark Comparison (greater than or equal to)
- (BOOL)isGreaterThanOrEqualToMajor:(int)major;
- (BOOL)isGreaterThanOrEqualToMajor:(int)major minor:(int)minor;
- (BOOL)isGreaterThanOrEqualToMajor:(int)major minor:(int)minor micro:(int)micro;
- (BOOL)isGreaterThanOrEqualToNumber:(int)number;
- (BOOL)isGreaterThanOrEqualTo:(Version *)aVersion;

Convenience constructors are listed below.

#pragma mark -
#pragma mark Convenience Constructors
+ (Version *)versionWithMajor:(int)major;
+ (Version *)versionWithMajor:(int)major minor:(int)minor;
+ (Version *)versionWithMajor:(int)major minor:(int)minor micro:(int)micro;
+ (Version *)versionWithString:(NSString *)string;


The following sample code shows how to implement System class that provides version method which returns a Version instance for iOS version.

// System.h
#import <Foundation/Foundation.h>
#import "Version.h"

@interface System : NSObject
/**
 * Get iOS version.
 */
+ (Version *)version;
@end

// System.m
#import <UIKit/UIDevice.h>
#import "System.h"

static Version *_version;

@implementation System
/**
 * Initialization for this class.
 */ 
+ (void)initialize
{
    // Get the system version of iOS at runtime.
    NSString *versionString = [[UIDevice currentDevice] systemVersion];

    // Convert the version string to a Version instance.
    Version *version = [Version versionWithString:versionString];

    // Set as a class variable.
    _version = version;
}

/**
 * Get iOS version.
 */
+ (Version *)version
{
    return _version;
}
@end

With System class implemented like above, code to check iOS version becomes shorter.

if (System.version.major >= 6)
{
    // iOS version is greater than or equal to 6.0.
}


Project Page
https://github.com/TakahikoKawasaki/nv-ios-version