본문 바로가기

Programming/iPhone, Xcode

Managed Object Context

Managed Object Context - NSManagedObjectContext


 - From Head First iPhone & iPad development 2nd edition


  • If you want to create a new instance of an NSManagedObject, you just do this: [NSEntityDescription insertNewObjectForEntityForName:@"Fugitive" in ManagedObjectContext:managedObjectContext];. The Managed Object Context is provided right from the start.
  • Most Core Data load/save operations point to an NSError in case something goes wrong. The "&" in Object-C behaves just like it does in C or C++ and returns the "address of the item. We declare a pointer to an NSError, then pass the address of that pointer into the save method in case something happens. If the save call fails, Core Data will populate that error argument with more detailed information. Keep in mind that just checking for an NSError does not work for determining if a method succeeded. For that, you should check the BOOL return value, since the error is only tracking if success was NO.
  • At a minimum, Core Data will validate objects before they're stored in the Persistence Store. So, it's possible that you could get a validation error when you try to save your changes if you have invalid data in one of your managed objects. To avoid such late notice, you should validate your NSManagedObjects as close to the time of changes as possible. You can explicitly validate a new NSManagedObject like this: [fugitive validateForInsert:&error]. Similarly, there are methods for validating updates and deletes. You can call these methods at any time to verify that the NSManagedObject is valid against constraints you put in the data model. If it's not, you can notify the user and ask them to correct the problem.




Managed Object Context 에서 변경된 것들을 저장하기 원치 않을 경우에는, rollback 을 사용하여, 새롭게 추가된 객체, 삭제, 이미 있는 객체들의 저장되지 않은 변경된 것들을 버릴 수 있다.


managed Object Context 는 Transaction 을 관리하는 녀석이라고 생각해도 된다. 여기서 Transaction 이라 함은 entity 들에게 변경을 주는 것을 의미 하는데, (i.e. 추가, 삭제, 저장과 동시에 commit, rollback 과 동시에 변경된 점이 버려지는 것)