iOS 開發系列:CoreData Object 變成 Fault 的一種方式

來源:互聯網
上載者:User

標籤:core   line   cat   官方文檔   ctc   art   str   san   組件   

@quote:

近來一直與 CoreData 打交道。這是一個架構龐大、學習曲線比較陡峭的 iOS 組件,每次遇到問題都會對其有新的認識。

這次就僅僅講一點,關於錯誤認知 Object(NSManagedObject)與 Context (NSManagedContext)的參考關聯性而導致的 Fault 問題。

用過 CoreData 的都應該對其基本使用有個最直接的瞭解,那就是:Object 都是放在 Context 裡的,同一時候 Object 也會有一個 「managedObjectContext」的方法,能夠得到它所在的 Context。

剛開始,我非常天然地以為,Context 強引用了 Object。Object 反過來也是引用了 Context。其實不是如此。Object 的 「managedObjectContext」是 method,而不是 property,這是沒有強參考關聯性的。

假如你從 CoreData Stack 建立了一個 Context,然後從這個 Context 裡取出來一個 Object。而且把這個 Object 指派給一個 ViewController。最後在這個 ViewController 裡進行一些任務,你非常快就會發現。Object 變成 fault 而無法使用了。

這是由於假設不相同強引用這個 Context,在它被釋放掉以後,Object 會由於沒有這個 Context 而導致「Fault cannot be fulfilled」進而無法使用。

關於「Fault cannot be fulfilled」。在 Apple 官方文檔「 Troubleshooting Core Data 」另一個範例,與我遇到的這個不太一樣。它所描寫敘述的情況是:從 Context 裡刪除了 Object 以後。實質內容已經被刪除。但 Object 由於在記憶體管理周期內還沒有被釋放掉。僅僅是變成了一個 Fault。這時假設再訪問這個 Object,就會得到「Fault cannot be fulfilled」的錯誤。

再回到我遇到的那個問題,通常在一個不是特別複雜的基於 CoreData 的程式其中,我們不會用到非常多個 Context。並且大家的 CoreData Stack 都是在 AppDelegate 層級強引用了 Context。尤其不會用到暫時建立的 Context 而忘記強引用它,因而這個問題也太不常見。

總之,看文檔的時候一定要注意區分 method 和 property,即使使用相同的文法+返回的是相同的東西。也不能認為它們是一回事。從這裡上來看,嚴格的使用 [object method] 和 object.property 這個文法還是有必要的。

------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

PS: 我查閱了API文檔,上面有句話一直不懂:

- (BOOL)isFault

Description

Returns a Boolean value that indicates whether the receiver is a fault.


Knowing whether an object is a fault is useful in many situations when computations are optional. It can also be used to avoid growing the object graph unnecessarily (which may improve performance as it can avoid time-consuming fetches from data stores).

If this method returns NO, then the receiver‘s data must be in memory. However, if this method returnsYES, it does not imply that the data is not in memory. The data may be in memory, or it may not, depending on many factors influencing caching

If the receiver is a fault, calling this method does not cause it to fire.  ////這句話真心不明確?還請大蝦賜教@@ 



iOS 開發系列:CoreData Object 變成 Fault 的一種方式

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.