'CoreData'에 해당되는 글 2건

  1. 2012.01.12 [IPHONE] Using Core Data
  2. 2011.12.29 [IPHONE] Core Data Core Competencies

[IPHONE] Using Core Data

CS/iPhone 2012. 1. 12. 23:20
원문 : http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/CoreData/cdProgrammingGuide.html

Managed Object

Custom implementation

- NSManagedObject의 서브클래스에 대해 작성하는 accessor methods의 구현에는 일반적으로 다른 클래스를 작성하는것과는 다르다.
  • 만약 custom instance variable을 제공하지 않는다면, primitive accessor method를 사용하여 internal store로 값을 저장하고, internal store로 부터 property value를 가져오게 된다. 
  • NSManagedObject 는 modeld properties에 대해서 automatic KVO  change notification 을 비활성화 하며, primitive accessor methods는 access notification method와 change notification method를 invoke하지 않는다.
  • Entity model에서 정의되지 않은 property들의 accessor method에서, automatic change notification을 활성화 하거나 적절한 change notification method를 invoke할 수 있다.

Creating

NSManagedObject *newEmployee = [NSEntityDescription insertNewObjectForEntityForName:@"Employee"

                                                             inManagedObjectContext:context];


NSManagedObject *newEmployee = [[NSManagedObject alloc] initWithEntity:employeeEntity

                                        insertIntoManagedObjectContext:context];



Entity Description

NSManagedObjectContext *context = <#Get a context#>;

NSManagedObjectModel *managedObjectModel = [[context persistentStoreCoordinator] managedObjectModel];

NSEntityDescription *employeeEntity = [[managedObjectModel entitiesByName] objectForKey:@"Employee"];


NSManagedObjectContext *context = <#Get a context#>;

NSEntityDescription *employeeEntity = [NSEntityDescription entityForName:@"Employee"

                                                  inManagedObjectContext:context];



Deleting

NSManagedObjectContext *context = <#Get a context#>;

[context deleteObject:managedObject];


- managed object context에 deleteObject: 메세지를 보내면, context는 NSManagedObjectContextObjectsDidChangeNotification 통지를 post한다.
- 만약 object가 동일한 transaction에서 create되고 delete 된다면, managed object context의 deletedObject 의 결과 array나 NSManagedObjectContextDidSaveNotification 통지의 deleted object set에 나타나지 않을 것이다. 



To-many relationships

NSMutableSet *employees = [aDepartment mutableSetValueForKey:@"employees"];

[employees addObject:newEmployee];

[employees removeObject:firedEmployee];


// or


[aDepartment addEmployeesObject:newEmployee];

[aDepartment removeEmployeesObject:firedEmployee];


- mutableSetValueForKey: 에 의해 리턴되는 값과 dot accessor method에 의해 리턴되는 값의 차이를 이해하는 것은 중요하다.
- mutableSetValueForKey:는  mutable proxy object를 리턴한다.
- 만약 그것의 내용을 바꾼다면, relationship에 대한 적절한 KVO change 통지를 emit 할 것이다. 
- dot accessor 는 단순히 set을 리턴한다.
- 만약 [aDepartment.employees addObject:newEmployee] 와 같이 한다면, KVO change notification은  emit 되지 않을 것이며, inverse relationship은 적절하게 update되지 않을 것이다. 
- dot 은 accessor method를 invoke 하기 떄문에, [[aDepartment employees] addObject:newEmployee]; 도 같은 결과이다. 



Manipulating Relationships and Object Graph Integrity

- Core Data 는 object graph의 consistency를 관리하기 때문에, 관계의 한쪽 끝만을 변경하면 다른 면은 Core Data 가 관리해 준다.


anEmployee.department = newDepartment;

or

[newDepartment addEmployeeObject:anEmployee]; 



Managed Object Context

Undo management

- 각 managed object context는 undo manager를 유지한다.
- Undo 비활성화

[context processPendingChanges]; // Flush operations for which you want undos

[[context undoManager] disableUndoRegistration];


// Make changes for which undo operations are not to be recorded

// ...


[context processPendingChanges]; // Flush operations for which you do not want undos

[[context undoManager] enableUndoRegistration];




Managed Object Model

Runtime에  NSManagedObjectModel 얻기

[[<#A managed object context#> persistentStoreCoordinator] managedObjectModel];
[[<#A managed object#> entity] managedObjectModel];  



Fetch

Fetching managed objects

NSManagedObjectContext *context = [self managedObjectContext];

NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Employee"

                                                     inManagedObjectContext:context];

NSFetchRequest *request = [[NSFetchRequest alloc] init];

[request setEntity:entityDescription];


NSNumber *minimumSalary = ...;

NSPredicate *predicate = [NSPredicate predicateWithFormat:

                          @"(lastName LIKE[c] 'Worsley') AND (salary > %@)", minimumSalary];

[request setPredicate:predicate];


NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"firstName" ascending:YES];

[request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];

[sortDescriptor release];


NSError *error = nil;

NSArray *array = [context executeFetchRequest:request error:&error];
[request release];
 

- transient properties에 기반한 predicate를 사용해서 fetch할 수는 없다.

 

Template 사용

NSManagedObjectModel *model = <#Get a model#>;

NSFetchRequest *requestTemplate = [[NSFetchRequest alloc] init];

NSEntityDescription *publicationEntity = [[model entitiesByName] objectForKey:@"Publication"];

[requestTemplate setEntity:publicationEntity]; 

NSPredicate *predicateTemplate = [NSPredicate predicateWithFormat:

                                  @"(mainAuthor.firstName like[cd] $FIRST_NAME) AND \

                                  (mainAuthor.lastname like[cd] $LST_NAME) AND \

                                  (publicationDate > $DATE)"]; 

[requestTemplate setPredicate:predicateTemplate]; 

[model setFetchRequestTemplate:requestTemplate forName:@"PublicationsForAuthorSinceDate"]; 

[requestTemplate release];

 

NSError *error = nil;

NSDictionary *substitutionDictionary = [NSDictionary dictionaryWithObjectsAndKeys:

                                        @"Fiona", @"FIRST_NAME",

                                        @"Verde", @"LAST_NAME",

                                        [NSDate dateWithTimeIntervalSinceNow:-31356000], @"DATE",

                                        nil];

NSFetchRequest *fetchRequest = [model fetchRequestFromTemplateWithName:@"PubliccationsForAuthorSinceDate"

                                                 substitutionVariables:substitutionDictionary]; 

NSManagedObjectContext *context = <#Get a managed object context#>;

NSArray *results = [context executeFetchRequest:fetchRequest error:&error];



Retrieving specific objects

NSManagedObjectContext *context = [self managedObjectContext];

NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Employee"

                                                     inManagedObjectContext:context];

NSFetchRequest *request = [[NSFetchRequest alloc] init];

[request setEntity:entityDescription];

[request release];


NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self == %@", targetObject];

[request setPredicate:predicate];


NSError *error = nil;

NSArray *array = [context executeFetchRequest:request error:&error];


:

[IPHONE] Core Data Core Competencies

CS/iPhone 2011. 12. 29. 21:39
: