2011-01-31 82 views
1

我厭倦了不斷地爲我的項目放置/重複NSFetchedResultsController代碼,幾乎在每個使用Managed Object Context的文件中。我可以把NSFetchedResultsController放在託管對象類中嗎?

我想減少重複代碼的數量。我想在模型類中放置這種類似於重複的類似CRUD的代碼。

我想取而代之的是把我所有的自定義NSFetchs的管理對象類內的相關實體(即:Company.m,Employee.m)。

即使從蘋果的核心書籍示例代碼不把這段代碼到管理對象類,如果它的可能,我想知道?

我試過的代碼粘貼到我的Company.m類,但它一直在抱怨managedObjectContext並且還抱怨說,fetchedResultsController未聲明,即使它的參數?

理想情況下,我想提出許多不同類型的讀取請求/結果控制器東西實體管理對象類裏面太的。

但在此之前我讓自己的未來,是否有可能,因此,只是把所有的東西NSFetchedResultsController實體管理對象類裏面?

如果有一個示例教程或項目或源代碼涵蓋了這一點,那也會很棒。

謝謝。

(代碼示例如下)。

/** 
Returns the fetched results controller. Creates and configures the controller if necessary. 
*/ 
- (NSFetchedResultsController *)fetchedResultsController 
{ 

    if (fetchedResultsController != nil) { 
     return fetchedResultsController; 
    } 

    // Create and configure a fetch request with the Book entity. 
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; 
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Company" inManagedObjectContext:managedObjectContext]; 
    [fetchRequest setEntity:entity]; 

    // Create the sort descriptors array. 
    NSSortDescriptor *authorDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]; 
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:authorDescriptor, nil]; 
    [fetchRequest setSortDescriptors:sortDescriptors]; 

    // Create and initialize the fetch results controller. 
    NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:@"author" cacheName:@"Root"]; 
    self.fetchedResultsController = aFetchedResultsController; 
    fetchedResultsController.delegate = self; 

    // Memory management. 
    [aFetchedResultsController release]; 
    [fetchRequest release]; 
    [authorDescriptor release]; 
    [sortDescriptors release]; 

    return fetchedResultsController; 
}  

回答

2

我推薦使用帶有xmod的ActiveRecord。如果修改核心數據模型,CoreData將覆蓋您的CRUD。 ActiveRecord使它像調用[MyManagedObject createEntity];NSArray *myObjects = [MyManagedObject findAll];一樣簡單。還有一些選項可以傳遞謂詞來過濾findAll調用。 xmod添加生成的類的子類,以便您可以添加自定義邏輯到您的實體,以便它們不會被覆蓋。

編輯:我想添加鏈接到這Active Record實現,因爲這是我實際使用的。

EDIT2:這個現在已經更名爲Magical Record

+0

好的,謝謝。 – zardon 2011-02-08 03:46:26

相關問題