Realm
Realm中有這句話:
Since Realm parses all models defined in your code at launch, they must all be valid, even if they are never used.
也就是說在啟動時所有的每個類該swizzle的方法都已經(jīng)處理完畢了。我第一反應(yīng)是利用load方法實現(xiàn),然而一查源代碼里并沒有l(wèi)oad方法。。。而且據(jù)說swift現(xiàn)在已經(jīng)不能override load方法了=。=
研究了下調(diào)用棧(故意把dynamic的屬性改成任意非Object子類的class,報錯后,console會輸出調(diào)用棧)和源碼得出結(jié)論:
Realm初始化方法中(間接)調(diào)用objc_copyClassList來獲得所有類,然后對其符合要求的類進(jìn)行swizzle(class_replaceMethod)
OC runtime 確實很強大。。。Realm源碼還是Swift、OC和C++混編,看來真正學(xué)好iOS的路還有很長。。。
還有這句話:
Applying KVC to a collection is a great way to update objects in bulk without the overhead of iterating over a collection while creating accessors for every item.
以前我一直認(rèn)為KVC一定會影響性能,官方文檔里也說
Though key-value coding is efficient, it adds a level of indirection that is slightly slower than direct method invocations. You should use key-value coding only when you can benefit from the flexibility that it provides.
這里為什么說還能提高性能呢?仔細(xì)再看了下KVC文檔意識到只要小心實現(xiàn)-replace<Key>AtIndexes:with<Key>: 是能夠?qū)⒈闅v更改請求優(yōu)化為一句SQL語句的,自然快很多。
update:
Predicate programming guide里也有這一句話,估計是類似的實現(xiàn)原理
If you use the Core Data framework, the array methods provide an efficient means of filtering an existing array of objects without—as a fetch does—requiring a round trip to a persistent data store.
Unless you need to make simultaneous writes from many threads at once, you should favor larger write transactions that do more work over many fine-grained write transactions.
Please note that when updating objects, nil is still considered a valid value for optional properties. If you supply a dictionary with nil property values, then these will be applied to your object and those properties will be emptied. To ensure you don’t experience any unplanned data loss, please make sure to provide only the properties you wish to update when using this method.
The following is not possible:
Casting between polymorphic classes (ie, subclass to subclass, subclass to parent, parent to subclass, etc.).
Querying on multiple classes simultaneously.
Multi-class containers (List and Results).Once the query has been executed, or a notification block has been added, the Results is kept up to date with changes made in the Realm, with the query execution performed on a background thread when possible.
The only time a Results is frozen is when fast-enumerating over it, which makes it possible to mutate the objects matching a query while enumerating over it:
Realm objects can only be accessed from the thread on which they were first created (Realm makes concurrent usage easy by ensuring that each thread always has a consistent view of the Realm. )
you must get a Realm instance in each thread/dispatch queue in which you want to read or write