realm數(shù)據(jù)使用還是有很多方便之處的荔燎,但是使用不當(dāng)?shù)脑?huà)耻姥,會(huì)覺(jué)得比較啰嗦的。
realm的數(shù)據(jù)對(duì)象RLMObject是直接連接到物理存儲(chǔ)的數(shù)據(jù)庫(kù)有咨,修改就直接改了數(shù)據(jù)庫(kù)里的數(shù)據(jù)了琐簇,也因此在對(duì)RLMObject類(lèi)型的數(shù)據(jù)進(jìn)行操作時(shí),要寫(xiě):
RLMRealm *realm = [RLMRealm defaultRealm];
[realm beginWriteTransaction];
//do something
[realm commitWriteTransaction];
有種避免的方法就是不持有這個(gè)指向realm數(shù)據(jù)庫(kù)的對(duì)象座享,如alloc婉商,init實(shí)例化一個(gè)A對(duì)象,此時(shí)它沒(méi)有存儲(chǔ)到realm數(shù)據(jù)庫(kù)渣叛,跟oc的對(duì)象操作是沒(méi)有啥區(qū)別丈秩;但是當(dāng)存儲(chǔ)到realm數(shù)據(jù)庫(kù),且指向了這個(gè)返回的對(duì)象淳衙,或是在realm的事務(wù)里創(chuàng)建的對(duì)象就會(huì)直接關(guān)聯(lián)到數(shù)據(jù)庫(kù)蘑秽。
下面這方式可以避免:按需是否持有返回的對(duì)象
+ (RLMObject *)addObjectToDB:(RLMObject *)obj {
RLMRealm *realm = [RLMRealm defaultRealm];
Class class = (RLMObject *)NSClassFromString([NSString stringWithUTF8String:object_getClassName(obj)]);
[realm beginWriteTransaction];
obj = [class createOrUpdateInRealm:realm withValue:obj];
[realm commitWriteTransaction];
return obj;
}
+ (void)deletDBObjects:(NSArray<RLMObject *> *)objs {
for (RLMObject *obj in objs) {
[self deletDBObject:obj];
}
}
+ (void)deletDBObject:(RLMObject *)obj {
RLMRealm *realm = [RLMRealm defaultRealm];
Class class = (RLMObject *)NSClassFromString([NSString stringWithUTF8String:object_getClassName(obj)]);
if (![class primaryKey]) {
return;
}
RLMObject *rlmObj = [class objectInRealm:realm forPrimaryKey:[obj valueForKey:[class primaryKey]]];
if (!rlmObj) {
return;
}
[realm transactionWithBlock:^{
[realm deleteObject:rlmObj];
}];
}
一開(kāi)始的設(shè)想就是建立一個(gè)通用的方法,方便各種類(lèi)型對(duì)象的操作箫攀,然后就是盡量的簡(jiǎn)化工程代碼肠牲。