2013-02-13 59 views
0

我有一個應用程序使用CoreData來存儲Customer實體。每個Customer實體都有一個customerName,customerID和其他屬性。CoreData和setPropertiesToFetch僅返回1實體

然後我顯示所有Customers的列表,只顯示他們的customerNamecustomerID

我可以通過執行獲取請求來抓取所有的Customer實體,但我只需要顯示customerNamecustomerID屬性。

問題1: 我試圖使用setPropertiesToFetch唯一尚未指定這些屬性每次只有數組中返回1個對象的時間。

這裏是我的方法是這樣的:

NSFetchRequest *fetchRequest = [NSFetchRequest new]; 


    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Customer" inManagedObjectContext:self.managedObjectContext]; 
    [fetchRequest setEntity:entity]; 

    NSDictionary *entProperties = [entity propertiesByName]; 

    [fetchRequest setResultType:NSDictionaryResultType]; 
    [fetchRequest setReturnsDistinctResults:YES]; 

    [fetchRequest setPropertiesToFetch:[NSArray arrayWithObjects:[entProperties objectForKey:@"customerName"],[entProperties objectForKey:@"customerID"], nil]]; 

    [fetchRequest setFetchLimit:30]; 

    NSError *error; 
    NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error]; 

    NSLog(@"fetched objects count = %d", [fetchedObjects count]); 

    if (error) { 
     NSLog(@"Error performing fetch = %@", [error localizedDescription]); 
     return nil; 
    } else { 
     NSLog(@"successful fetch of customers"); 
     for(NSDictionary* obj in fetchedObjects) { 
      NSLog(@"Customer: %@", [obj objectForKey:@"customerName"]); 
     } 
     return fetchedObjects; 
    } 

返回的一個對象就可以了,所以我知道這是抓住至少一個Customer對象customerNamecustomerID。我只需要它返回所有Customer對象customerNamecustomerID

問題2:

這是在做這個的最好方法?我的想法是數據庫中可能有多達10k個客戶對象。因此,只需獲取所需的屬性即可顯示在表格中,而不是整個對象上,從而提高內存效率。

然後,當在表格中選擇一個客戶時,我獲取整個Customer對象以顯示其詳細信息。

但是,我讀過,加載整個實體,而不是隻是它的屬性,如果相應的實體可以在不久的將來使用它也是一個好習慣。我想這個想法是,單個獲取請求比兩個要好。

謝謝你的幫助。

+0

如果刪除提取限制,會發生什麼情況? – ChrisH 2013-02-14 15:49:21

回答

0

隨機,

問題2: 這聽起來像你正在使用的時候,你應該使用批處理限制的擷取限制。批量限制是一種基本的遊標機制。它們旨在有效處理內存。

W.r.t.問題1,我非常相信只是以自然的方式編寫應用程序,然後使用儀器和其他工具來決定性能和內存優化。嘗試讓應用程序首先正確運行。然後加快速度。

Andrew

2

對於問題1:這裏是我用swift編寫的示例代碼。我不斷地測試CoreData API,並找到這種調用方式。希望能幫助你。

let fetchRequest = NSFetchRequest<NSDictionary>(entityName: "Customer") 
fetchRequest.resultType = .dictionaryResultType 
fetchRequest.propertiesToFetch = [ 
    #keyPath(Customer.customerID), 
    #keyPath(Customer.customerName) 
] 

let customers: [NSDictionary] 
do { 
    customers = try managedObjectContext.fetch(fetchRequest) 
    customers.forEach { 
     print("CustomerID: \($0["customerID"]), CustomerName: \($0["customerName"])") 
    } 
} catch { 
    print(error.localizedDescription) 
}