我正在使用核心數據編寫我的第一個綜合應用程序,我想查看跟蹤各種對象更改/更新/刪除的最佳方法。例如,我有一個Notes實體和一個Location實體,以及它們之間的一對一關係,這個想法是每個筆記都可以標記它的位置。然後,我有一個帶有fetchedResultsController的UITableView,它驅動筆記列表(您可以在其中添加新筆記並附加日期和位置),但是之後我有兩個其他視圖控制器,一個具有地圖視圖,另一個具有日曆視圖。地圖視圖提取位置中的所有位置並將其顯示在地圖上。日曆視圖基本上從Notes獲取所有數據,並僅在日曆視圖中顯示它。 我應該如何跟蹤日曆和地圖視圖中Notes和Location的更改?在viewDidLoad中加載它們很容易,但我應該如何跟蹤所有更改,以便當用戶重新訪問地圖視圖時(例如)他/她也可以看到最新數據。最佳實踐 - iOS中的NSManagedObjectContextObjectsDidChangeNotification
我解密的一種方法是在NSManagedObjectContextObjectsDidChangeNotification中偵聽地圖視圖和日曆視圖中的通知。這似乎從管理的上下文中返回所有插入,刪除和更新的對象,每次都有保存。然後我可以瀏覽這些對象,看看是否需要更新我的視圖。這是我在想這樣做的:
在MapViewController中viewDidLoad中:
[[NSNotificationCenter defaultCenter]
addObserver: self
selector: @selector(objectChangedNotificationReceived:)
name: NSManagedObjectContextObjectsDidChangeNotification
object: context];
然後:
- (void) objectChangedNotificationReceived: (NSNotification *) notification
{
NSArray* insertedObjects = [[notification userInfo]
objectForKey:NSInsertedObjectsKey] ;
NSArray* deletedObjects = [[notification userInfo]
objectForKey:NSDeletedObjectsKey] ;
NSArray* updatedObjects = [[notification userInfo]
objectForKey:NSUpdatedObjectsKey] ;
NSLog(@"insertObjects: %@", [insertedObjects description]);
NSLog(@"deletedObjects: %@", [deletedObjects description]);
NSLog(@"updatedObjects: %@", [updatedObjects description]);
for (NSManagedObject *obj in insertedObjects) {
if ([obj class] == [Location class]) {
NSLog(@"adding a new location");
Location *locationObj = (Location *) obj;
[self.mapview addAnnotation: locationObj];
}
}
}
這個問題似乎有關的權利?好像有很多冗餘代碼放在每個視圖控制器中,特別是當我對多個NSManagedObject感興趣時。有沒有其他的技術,我錯過了?
儘管我的視圖沒有與它們關聯的表視圖,但我確實使用了NSFetchedResultsController,它的工作方式就像一個魅力! –
@ZS顯然,「NSFetchedResultsController」與tableView沒有關係。 –