操作CoreData 常見的錯誤及解決方案

來源:互聯網
上載者:User

. 使用Core Data時Model Class的定義:

  • property必須是Objective C的物件類型,必須聲明為nonatomic & retain或 nonatomic
  • 在.m檔案中accessor方法用@dynamic, refenrence裡面是strongly recommend這樣用的
  • 如果property是數字,用NSNumber *,調用的時候再換成需要的類型。
    • 例如 cell.text = [NSNumber stringValue: (NSNumber *)];

2. 修改.xcdatamodel檔案引起的Exception

  • 如果在程式已經運行過的情況下更改了.xcdatamodel檔案,原有資料庫就作廢了,所以無論怎麼調試都會出現exception。一般console裡面會提示NSPersistentStoreCoordinator has no persistent stores.
  • 解決方案:找到.sqlite,然後刪掉,重新運行。.sqlite檔案在Library/Application

    Support/iPhone Simulator/User/Applications/(一堆數字,點進去會看見project名)/Documents/
  • 詳細參考:http://objitsu.com/blog/2009/10/01/nspersistentstorecoordinator-has-no-persistent-stores/

3. 所有跟text有關的UI類的setText方法只能用NSString,否則會有warning,如果不管這個warning運行時會exception.

4. 如何調試EXE_BAD_ACCESS

  • 詳細參考:http://www.codza.com/how-to-debug-exc_bad_access-on-iphone

5. unrecognized selector sent to instance xxxx

  • 造成unrecognized selector sent to instance iphone,大部分情況下是因為對象被提前release了,在你心裡不希望他release的情況下,指標還在,對象已經不在了。很多時候,是因為init初始化函數中,對屬性賦值沒有使用self.foo賦值,而是直接對foo賦值,導致屬性對象沒有retain(心裡以為retain了),而提前釋放。有時候也能是初始化函數用錯了。
  • 解決方案:檢查release和init

6. Can’t merge models with two different entities named xxxx

  • 修改了Core Data的資料模型後,因為版本問題出現的Exception
  • 解決辦法:Build —>clear all target
  • 參考資料:Core Data Migration and Version
    • http://www.timisted.net/blog/archive/core-data-migration/

7. could not locate an NSManagedObjectModel for entity name

  • managedObjectContext沒有初始化,所以無法讀取model的值
  • 調試方法:將appDelegate的context傳給viewController前,要將viewController的context初始化,囧囧是寫在initWithNibName裡的 

8.UITableView的資料來源排序為降序時,記得CellForRowAtIndexPath裡面不要用if(Cell ==nil)的條件去掉,否則資料更新會錯。。。

9.  使用Core Data時,實體類的relationship在fetch的時候只作為fault被調用

fault是為了保證模型完整的一種東西,比如說A有個relationship ,這個關係的目標是B,那fetch A的時候,B只是個fault,你是無法訪問B的屬性的,因為B根本沒被fetch ,下面是囧囧的解決方案,也不知道對不對,哈哈哈哈- - 

 [fetchRequest setReturnsObjectsAsFaults:NO]; 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.