2015年1月29日 星期四

Realm 0.89.0先期研究

近期出現了Realm這個新的mobile database,先做點筆記。
Document: http://realm.io/docs/cocoa/0.89.0/

Subclass RLMObject

// Dog.h
 @interface Dog : RLMObject
 @property NSString *name;
 @property BOOL      adopted;
 @end

 // Dog.m
 @implementation Dog
 @end //none needed

目前Model物件必須subclass RLMObject。RLMObject只能在創建它的thread內使用。

Supported property types

NSString
NSInteger, CGFloat, int, long, float, and double
BOOL or bool
NSDate
NSData
RLMObject subclasses, so you can have many-to-one relationships.
RLMArray < X >, where X is an RLMObject subclass, so you can have many-to-many relationships.

Write

// Create object
Person *author = [[Person alloc] init];
author.name    = @"David Foster Wallace";

// Get the default Realm
RLMRealm *realm = [RLMRealm defaultRealm];
// You only need to do this once (per thread)

// Add to Realm with transaction
[realm beginWriteTransaction];
[realm addObject:author];
[realm commitWriteTransaction];

// Update an object with a transaction
[realm beginWriteTransaction];
author.name = @"Thomas Pynchon";
[realm commitWriteTransaction];

所有對物件的新增修改刪除都必須包在WriteTransaction裡,因為在RLMObject裏的所有ivar都是跟資料庫直接相連的,而不是一般我們習慣的memory。http://stackoverflow.com/a/25002895/1060971 說明了所有對物件property的修改都會被同步進database。

PrimaryKey

在設計Model物件時,PrimaryKey絕對是不可或缺的property之一。在不同的thread之間無法互相傳遞RLMObject使用,因為RLMObject只能在創建它的thread內使用。所以我們只能透過在非main thread查詢到物件的PrimaryKey,然後把PrimaryKey傳到main thread,然後再

[MyObject objectsWhere:"primaryId IN %@", idArray];

獲得一個新的RLMObject,然後才在main thread使用這個新的RLMObject。
參考:https://groups.google.com/d/msg/realm-cocoa/naRBh-WMet0/ONPvTCGaSUkJ

產生primary key的方式常見有兩種,一是流水號,二是uuid。
產生流水號的method在multi-thread環境下記得保證其thread-safe,否則很可能會產生相同的流水號。
uuid的話,在multi-thread環境下直接產生就好,因為衝突機率很小。

[[NSUUID UUID] UUIDString];

參考:http://stackoverflow.com/a/26257616/1060971

沒有留言:

張貼留言