我最近將我的Realm庫從0.92(我認爲)升級到0.96.2,但是在「可選」屬性的新支持方面遇到了一些麻煩。我還需要首次進行移徙,這也是一件複雜的事情。領域遷移和可選屬性
到單個字段添加到數據類型中的一種需要新的方案,所以我編寫了一個遷移是建立在現有的對象這個新屬性:
RLMRealmConfiguration* config = [RLMRealmConfiguration defaultConfiguration];
config.schemaVersion = 1;
config.migrationBlock = ^(RLMMigration* migration, uint64_t oldSchemaVersion)
{
[migration enumerateObjects:Foo.className
block:^(RLMObject* oldObject, RLMObject* newObject) {
if (oldSchemaVersion < 1)
{
newObject[@"user"] = @"";
}
}];
};
[RLMRealmConfiguration setDefaultConfiguration:config];
然而,一旦代碼試圖打開一個境界,我得到一個錯誤信息有關可選屬性類型:
'Migration is required for object type 'Person' due to the following errors:
- Property 'name' has been made optional.
- Property ‘company’ has been made optional.
- Property 'title' has been made optional.
- Property 'phone' has been made optional.
- Property 'email' has been made optional.
- Property 'homeAddress' has been made optional.'
問題#1 - 由於模型是從「必要」的屬性將「可選」,還有的保證是一個值ALR對現有物體存在;所以我很努力地看到爲什麼遷移是要求。
問題2 - 我還是喜歡會遷移的對象,無出的屬性,如果該字符串是空的,所以我編寫了一個遷移:
RLMRealmConfiguration* config = [RLMRealmConfiguration defaultConfiguration];
config.schemaVersion = 1;
config.migrationBlock = ^(RLMMigration* migration, uint64_t oldSchemaVersion)
{
NSLog(@"RUNNING REALM MIGRATION");
// ...basic migration of adding a new property (above)
[migration enumerateObjects:Person.className
block:^(RLMObject* oldObject, RLMObject* newObject) {
if (oldSchemaVersion < 1)
{
if ([oldObject[@"name"] length] == 0)
newObject[@"name"] = nil;
else
newObject[@"name"] = oldObject[@"name"];
// … repeat for other properties
}
}];
};
[RLMRealmConfiguration setDefaultConfiguration:config];
然而,遷移似乎沒有運行; if (oldSchemaVersion < 1)
塊內的斷點不會被打中,並且"RUNNING REALM MIGRATION"
消息不會打印。
外塊 - 建立RLMRealmConfiguration
- 被擊中裏面application:didFinishLaunchingWithOptions:
謝謝,我沒有注意到,我會翻轉枚舉和條件塊。我仍然有同樣的問題:'config。migrationBlock'似乎並沒有被執行。 – Chris
需要進行遷移才能將這些以前需要的屬性轉換爲可選屬性。 - 這個怎麼做? - 我試過了,只需要一次遷移,即使它是空的。 –