SlideShare ist ein Scribd-Unternehmen logo
1 von 29
Downloaden Sie, um offline zu lesen
Core Data
                iz iPhone vidika




                           Matej Bukovinski
                           www.bukovinski.com




sreda, 16. december 2009
Agenda
                •    Malo teorije (z kodo)
                •    Malo prakse (preprost Xcode demo)
                •    Q&A




sreda, 16. december 2009
Core Data
                1. del, Teorija




sreda, 16. december 2009
Core data
                •    Mehanizmi za upravljaje z objektnim grafom in
                     življenjskim ciklom objektov
                •    Zagotavlja trajnost podatkov (presistence)
                •    Enostavnejši način za ravnanje z MVC Model objekti
                •    Framework (CoreData.framework)
                •    Sestavni del Cocoa API-ja od Mac OS X 10.4
                •    Sestavni del Cocoa-touch od iPhone OS 3.0



sreda, 16. december 2009
Prednosti
                •    Model objekte preprosto narišemo (z relacijami!) v
                     entitetnem modelu (včasih popolnoma brez kode)

                •    Znebimo se ogromno kode za zagotavljanje trajnosti
                     podatkov (nalaganje, shranjevanje,...)

                •    Učinkovitost (hitrejše in pogosto manj pomnilniško
                     zahtevno kot direktni SQL pristop)

                •    Priročne metode za poizvedovanje in optimizacijo

                •    Faulting (povezani objekt se po potrebi samodejno naloži)

                •    Undo manager


sreda, 16. december 2009
Slabosti
                •    Nekateri (Aaron) imajo rajši popolni nadzor nad tem
                     kaj se dogaja z objekti v ozadju




sreda, 16. december 2009
Core Data sklad

                            NSManagedObjectContext
                             NSManagedObject    NSManagedObject
                              NSManagedObject    NSManagedObject




                           NSPresistentStoreCoordinator

     Entitetni model


                                    NSPresistentStore

                                                                   Podatkovna shramba
                                                                       (npr. SQLite)
sreda, 16. december 2009
Core Data sklad

                            NSManagedObjectContext
                             NSManagedObject    NSManagedObject
                              NSManagedObject    NSManagedObject




                           NSPresistentStoreCoordinator

     Entitetni model


                                    NSPresistentStore

                                                                   Podatkovna shramba
                                                                         (SQL, ...)
sreda, 16. december 2009
Core Data, uporaba v praksi

                   1                                                  2

                                                                           NSManagedObjectContext
                                                                            NSManagedObject     NSManagedObject
                                                                             NSManagedObject     NSManagedObject



                           Entitetni model                                                          +
                                                                                           NSFetchRequest


                           • Narišemo (ali spišemo) entitetni             • Nad NSManagedObjectContext izvajamo splošne
                             model, ki predstavlja naše poslovne            operacije (shranjevanje, nalaganje, dodajanje modelnih
                             objekte                                        objektov)
                           • Tu določimo entitete, razmerja med           • Poizvedbe oblikujemo z NSFechRequest (podobno kot
                             njimi entitetami, atibute, omejitve...         SQL)
                           • Po potrebi generiramo izvorno kodo v         • Entitete so predstavljene z objekti, ki dedujejo od
                             kateri lahko dodajamo dodatno logiko           NSManagedObject, z njimi ravnamo kot z običajnimi
                             modelnim objektov                              Objective-C objekti



sreda, 16. december 2009
Inicializacija
                1. Naložimo entitetni model (NSManagedObjectModel)
                2. Ustvarimo koordinatorja (NSPresistentStore-
                   Coordinator) in ga povežemo z modelom
                3. Dodamo shrambo (NSPresistentStore)
                4. Ustvarimo kontekst (NSManagedObjectContext) in ga
                   povežemo s koordinatorjem




sreda, 16. december 2009
Inicializacija
                1. Naložimo entitetni model (NSManagedObjectModel)
                2. Ustvarimo koordinatorja (NSPresistentStore-
                   Coordinator) in ga povežemo z modelom
                3. Dodamo shrambo (NSPresistentStore)
                4. Ustvarimo kontekst (NSManagedObjectContext) in ga
                   povežemo s koordinatorjem


                           Če izberemo pravi Xcode template je to za nas
                                         že poskrbljeno!

sreda, 16. december 2009
Nalaganje iz shrambe
                      // Ustvarimo fetch request (poizvedba)
                NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init] autorelease];
                // Povemo katera entiteta nas zanima
                NSEntityDescription *entity = [NSEntityDescription entityForName:@"Song"
                inManagedObjectContext:self.managedObjectContext];
                [fetchRequest setEntity:entity];
                // Povemo kako želimo sortirati (opcijsko)
                NSSortDescriptor *sortDescriptor = [[[NSSortDescriptor alloc]
                initWithKey:@"title" ascending:YES] autorelease];
                NSArray *sortDescriptors = [[NSArray arraytWithObjects:sortDescriptor,
                nil];
                [fetchRequest setSortDescriptors:sortDescriptors];
                // Naredimo poizvedbo in s tem ustvarimo naše objekte
                NSError *error;
                NSArray *songs = [managedObjectContext executeFetchRequest:request
                error:&error];




sreda, 16. december 2009
Nalaganje iz shrambe
                // Ustvarimo fetch request (poizvedba)
                NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init] autorelease];
                // Povemo katera entiteta nas zanima
                NSEntityDescription *entity = [NSEntityDescription entityForName:@"Song"
                inManagedObjectContext:self.managedObjectContext];
                [fetchRequest setEntity:entity];
                // Povemo kako želimo sortirati (opcijsko)
                NSSortDescriptor *sortDescriptor = [[[NSSortDescriptor alloc]
                initWithKey:@"title" ascending:YES] autorelease];
                NSArray *sortDescriptors = [[NSArray arraytWithObjects:sortDescriptor,
                nil];
                [fetchRequest setSortDescriptors:sortDescriptors];
                // Naredimo poizvedbo in s tem ustvarimo naše objekte
                NSError *error;
                NSArray *songs = [managedObjectContext executeFetchRequest:request
                error:&error];




sreda, 16. december 2009
Nalaganje iz shrambe
                // Ustvarimo fetch request (poizvedba)
                NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init] autorelease];
                // Povemo katera entiteta nas zanima
                NSEntityDescription *entity = [NSEntityDescription entityForName:@"Song"
                inManagedObjectContext:self.managedObjectContext];
                [fetchRequest setEntity:entity];
                // Povemo kako želimo sortirati (opcijsko)
                NSSortDescriptor *sortDescriptor = [[[NSSortDescriptor alloc]
                initWithKey:@"title" ascending:YES] autorelease];
                NSArray *sortDescriptors = [[NSArray arraytWithObjects:sortDescriptor,
                nil];
                [fetchRequest setSortDescriptors:sortDescriptors];
                // Naredimo poizvedbo in s tem ustvarimo naše objekte
                NSError *error;
                NSArray *songs = [managedObjectContext executeFetchRequest:request
                error:&error];




sreda, 16. december 2009
Nalaganje iz shrambe
                // Ustvarimo fetch request (poizvedba)
                NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init] autorelease];
                // Povemo katera entiteta nas zanima
                NSEntityDescription *entity = [NSEntityDescription entityForName:@"Song"
                inManagedObjectContext:self.managedObjectContext];
                [fetchRequest setEntity:entity];
                // Povemo kako želimo sortirati (opcijsko)
                NSSortDescriptor *sortDescriptor = [[[NSSortDescriptor alloc]
                initWithKey:@"title" ascending:YES] autorelease];
                NSArray *sortDescriptors = [[NSArray arraytWithObjects:sortDescriptor,
                nil];
                [fetchRequest setSortDescriptors:sortDescriptors];
                // Naredimo poizvedbo in s tem ustvarimo naše objekte
                NSError *error;
                NSArray *songs = [managedObjectContext executeFetchRequest:request
                error:&error];




sreda, 16. december 2009
Shranjevanje sprememb
                NSError *error;
                // Če ni sprememb ni potrebno shranjevati
                if ([managedObjectContext hasChanges]) {
                $ // Shranjevanje vseh sprememb - 1 vrstica kode!
                $ if (![managedObjectContext save:&error]) {
                $ $        // Poskrbi za napako
                $ }
                }




sreda, 16. december 2009
Shranjevanje sprememb
                NSError *error;
                // Če ni sprememb ni potrebno shranjevati
                if ([managedObjectContext hasChanges]) {
                $ // Shranjevanje vseh sprememb - 1 vrstica kode!
                $ if (![managedObjectContext save:&error]) {
                $ $        // Poskrbi za napako
                $ }
                }




sreda, 16. december 2009
Dodajanje novih objektov
                // Ponavadi uporabljamo NSEntityDescription za ustvarjanje novih entitet
                Song *newSong = [NSEntityDescription
                $ $        $   $   $   insertNewObjectForEntityForName:@"Song"
                $ $        $   $   $   inManagedObjectContext:self.managedObjectContext];
                // Sedaj imamo Objective-C objekt, ki je umeščen v kontekst
                // Z njim ravnamo kot z vsemi drugimi objekti
                newSong.title = @"Yellow Submarine";




sreda, 16. december 2009
Dodajanje novih objektov
                // Ponavadi uporabljamo NSEntityDescription za ustvarjanje novih entitet
                Song *newSong = [NSEntityDescription
                $ $        $   $   $   insertNewObjectForEntityForName:@"Song"
                $ $        $   $   $   inManagedObjectContext:self.managedObjectContext];
                // Sedaj imamo Objective-C objekt, ki je umeščen v kontekst
                // Z njim ravnamo kot z vsemi drugimi objekti
                newSong.title = @"Yellow Submarine";




sreda, 16. december 2009
Brisanje objektov
                // Samo podamo konkretno “Song” instanco
                [self.managedObjectContext deleteObject:song];




sreda, 16. december 2009
NSFetchedResultsController
                •    Poenostavlja delo z UITableView pri uporabi Core
                     Data
                •    Podamo NSFetchRequest, način sortiranja in
                     grupiranja
                •    V UITableViewDataSource metodah kličemo metode
                     na NSFetchedResultsContoller-ju in dobimo
                     potrebne podatke za populacijo tabele
                •    Učinkovito (nalaganje v skupinah, sprostitev
                     nevidnih objektov, uporaba predpomnjenja)


sreda, 16. december 2009
NSFetchedResultsController
                inicializacija
                // Pred tem ustrezno pripravimo fetchRequest
                self.fetchController = [[[NSFetchedResultsController alloc]
                $ $        $   $   $   $   initWithFetchRequest:fetchRequest
                $ $        $   $   $   $   managedObjectContext:self.managedObjectContext
                $ $        $   $   $   $   sectionNameKeyPath:@"artist"
                $ $        $   $   $   $   cacheName:@"songsCache"] autorelease];


                NSError *error;
                BOOL success = [self.fetchController performFetch:&error];


                if (!success) {
                $ // Napaka..
                }




sreda, 16. december 2009
NSFetchedResultsController
                inicializacija
                // Pred tem ustrezno pripravimo fetchRequest
                self.fetchController = [[[NSFetchedResultsController alloc]
                $ $        $   $   $   $   initWithFetchRequest:fetchRequest
                $ $        $   $   $   $   managedObjectContext:self.managedObjectContext
                $ $        $   $   $   $   sectionNameKeyPath:@"artist"
                $ $        $   $   $   $   cacheName:@"songsCache"] autorelease];


                NSError *error;
                BOOL success = [self.fetchController performFetch:&error];


                if (!success) {
                $ // Napaka..
                }




sreda, 16. december 2009
NSFetchedResultsController
                uporaba (1 od 2)
                - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
                $ // Hrošč pri 3.0, glej NSFetchedResultsController dokumentacijo, 3.1 OK
                $ return [[self.fetchController sections] count];
                }


                - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:
                (NSInteger)section {
                $ id <NSFetchedResultsSectionInfo> sectionInfo =
                $ $        $   [[fetchController sections] objectAtIndex:section];
                $ return [sectionInfo numberOfObjects];
                }


                - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:
                (NSInteger)section {
                $ $        id <NSFetchedResultsSectionInfo> sectionInfo =
                $ $        $   [[fetchController sections] objectAtIndex:section];
                       return [sectionInfo name];
                }
sreda, 16. december 2009
NSFetchedResultsController
                uporaba (1 od 2)
                - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
                $ // Hrošč pri 3.0, glej NSFetchedResultsController dokumentacijo, 3.1 OK
                $ return [[self.fetchController sections] count];
                }


                - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:
                (NSInteger)section {
                $ id <NSFetchedResultsSectionInfo> sectionInfo =
                $ $        $   [[fetchController sections] objectAtIndex:section];
                $ return [sectionInfo numberOfObjects];
                }


                - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:
                (NSInteger)section {
                $ $        id <NSFetchedResultsSectionInfo> sectionInfo =
                $ $        $   [[fetchController sections] objectAtIndex:section];
                       return [sectionInfo name];
                }
sreda, 16. december 2009
NSFetchedResultsController
                uporaba (1 od 2)
                - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
                $ // Hrošč pri 3.0, glej NSFetchedResultsController dokumentacijo, 3.1 OK
                $ return [[self.fetchController sections] count];
                }


                - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:
                (NSInteger)section {
                $ id <NSFetchedResultsSectionInfo> sectionInfo =
                $ $        $   [[fetchController sections] objectAtIndex:section];
                $ return [sectionInfo numberOfObjects];
                }


                - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:
                (NSInteger)section {
                $ $        id <NSFetchedResultsSectionInfo> sectionInfo =
                $ $        $   [[fetchController sections] objectAtIndex:section];
                       return [sectionInfo name];
                }
sreda, 16. december 2009
NSFetchedResultsController
                uporaba (2 od 2)
                - (UITableViewCell *)tableView:(UITableView *)tableView
                cellForRowAtIndexPath:(NSIndexPath *)indexPath {


                $ static NSString *CellIdentifier = @"SongCell";
                $ UITableViewCell *cell = [tableView
                $ $        $   dequeueReusableCellWithIdentifier:CellIdentifier];


                $ if (cell == nil) {
                $ $        cell = [[[UITableViewCell alloc]
                $ $        $   $   initWithStyle:UITableViewCellStyleSubtitle
                $ $        $   $   reuseIdentifier:CellIdentifier] autorelease];
                $ }
                $ Song *song = (Song *)[fetchController objectAtIndexPath:indexPath];
                $ cell.textLabel.text = song.title;
                $ cell.detailTextLabel.text = song.genre;
                $ return cell;
                }


sreda, 16. december 2009
Core Data
                2. del, Praksa - demo time




sreda, 16. december 2009
Core Data
                3. del, Q&A




sreda, 16. december 2009

Weitere ähnliche Inhalte

Kürzlich hochgeladen

Bahare Shariat Jild 2 By SadurshSharia Mufti Amjad Ali Azmi
Bahare Shariat Jild 2 By SadurshSharia Mufti Amjad Ali AzmiBahare Shariat Jild 2 By SadurshSharia Mufti Amjad Ali Azmi
Bahare Shariat Jild 2 By SadurshSharia Mufti Amjad Ali Azmibookbahareshariat
 
TUYỂN TẬP 25 ĐỀ THI HỌC SINH GIỎI MÔN TIẾNG ANH LỚP 6 NĂM 2023 CÓ ĐÁP ÁN (SƯU...
TUYỂN TẬP 25 ĐỀ THI HỌC SINH GIỎI MÔN TIẾNG ANH LỚP 6 NĂM 2023 CÓ ĐÁP ÁN (SƯU...TUYỂN TẬP 25 ĐỀ THI HỌC SINH GIỎI MÔN TIẾNG ANH LỚP 6 NĂM 2023 CÓ ĐÁP ÁN (SƯU...
TUYỂN TẬP 25 ĐỀ THI HỌC SINH GIỎI MÔN TIẾNG ANH LỚP 6 NĂM 2023 CÓ ĐÁP ÁN (SƯU...Nguyen Thanh Tu Collection
 
FAIL REKOD PENGAJARAN.pptx fail rekod pengajaran
FAIL REKOD PENGAJARAN.pptx fail rekod pengajaranFAIL REKOD PENGAJARAN.pptx fail rekod pengajaran
FAIL REKOD PENGAJARAN.pptx fail rekod pengajaransekolah233
 
Bahare Shariat Jild 4 By SadurshSharia Mufti Amjad Ali Azmi
Bahare Shariat Jild 4 By SadurshSharia Mufti Amjad Ali AzmiBahare Shariat Jild 4 By SadurshSharia Mufti Amjad Ali Azmi
Bahare Shariat Jild 4 By SadurshSharia Mufti Amjad Ali Azmibookbahareshariat
 
Bahare Shariat Jild 3 By SadurshSharia Mufti Amjad Ali Azmi
Bahare Shariat Jild 3 By SadurshSharia Mufti Amjad Ali AzmiBahare Shariat Jild 3 By SadurshSharia Mufti Amjad Ali Azmi
Bahare Shariat Jild 3 By SadurshSharia Mufti Amjad Ali Azmibookbahareshariat
 
Bahare Shariat Jild 5 By SadurshSharia Mufti Amjad Ali Azmi
Bahare Shariat Jild 5 By SadurshSharia Mufti Amjad Ali AzmiBahare Shariat Jild 5 By SadurshSharia Mufti Amjad Ali Azmi
Bahare Shariat Jild 5 By SadurshSharia Mufti Amjad Ali Azmibookbahareshariat
 
TUYỂN TẬP 20 ĐỀ THI KHẢO SÁT HỌC SINH GIỎI MÔN TIẾNG ANH LỚP 6 NĂM 2020 (CÓ Đ...
TUYỂN TẬP 20 ĐỀ THI KHẢO SÁT HỌC SINH GIỎI MÔN TIẾNG ANH LỚP 6 NĂM 2020 (CÓ Đ...TUYỂN TẬP 20 ĐỀ THI KHẢO SÁT HỌC SINH GIỎI MÔN TIẾNG ANH LỚP 6 NĂM 2020 (CÓ Đ...
TUYỂN TẬP 20 ĐỀ THI KHẢO SÁT HỌC SINH GIỎI MÔN TIẾNG ANH LỚP 6 NĂM 2020 (CÓ Đ...Nguyen Thanh Tu Collection
 
Bahare Shariat Jild 1 By SadurshSharia Mufti Amjad Ali Azmi
Bahare Shariat Jild 1 By SadurshSharia Mufti Amjad Ali AzmiBahare Shariat Jild 1 By SadurshSharia Mufti Amjad Ali Azmi
Bahare Shariat Jild 1 By SadurshSharia Mufti Amjad Ali Azmibookbahareshariat
 
مختصر علم احكام القرآن فقه القرآن وفق منهج العرض
مختصر علم احكام القرآن فقه القرآن وفق منهج العرضمختصر علم احكام القرآن فقه القرآن وفق منهج العرض
مختصر علم احكام القرآن فقه القرآن وفق منهج العرضأنور غني الموسوي
 

Kürzlich hochgeladen (11)

Energy drink .
Energy drink                           .Energy drink                           .
Energy drink .
 
Bahare Shariat Jild 2 By SadurshSharia Mufti Amjad Ali Azmi
Bahare Shariat Jild 2 By SadurshSharia Mufti Amjad Ali AzmiBahare Shariat Jild 2 By SadurshSharia Mufti Amjad Ali Azmi
Bahare Shariat Jild 2 By SadurshSharia Mufti Amjad Ali Azmi
 
TUYỂN TẬP 25 ĐỀ THI HỌC SINH GIỎI MÔN TIẾNG ANH LỚP 6 NĂM 2023 CÓ ĐÁP ÁN (SƯU...
TUYỂN TẬP 25 ĐỀ THI HỌC SINH GIỎI MÔN TIẾNG ANH LỚP 6 NĂM 2023 CÓ ĐÁP ÁN (SƯU...TUYỂN TẬP 25 ĐỀ THI HỌC SINH GIỎI MÔN TIẾNG ANH LỚP 6 NĂM 2023 CÓ ĐÁP ÁN (SƯU...
TUYỂN TẬP 25 ĐỀ THI HỌC SINH GIỎI MÔN TIẾNG ANH LỚP 6 NĂM 2023 CÓ ĐÁP ÁN (SƯU...
 
FAIL REKOD PENGAJARAN.pptx fail rekod pengajaran
FAIL REKOD PENGAJARAN.pptx fail rekod pengajaranFAIL REKOD PENGAJARAN.pptx fail rekod pengajaran
FAIL REKOD PENGAJARAN.pptx fail rekod pengajaran
 
Bahare Shariat Jild 4 By SadurshSharia Mufti Amjad Ali Azmi
Bahare Shariat Jild 4 By SadurshSharia Mufti Amjad Ali AzmiBahare Shariat Jild 4 By SadurshSharia Mufti Amjad Ali Azmi
Bahare Shariat Jild 4 By SadurshSharia Mufti Amjad Ali Azmi
 
Bahare Shariat Jild 3 By SadurshSharia Mufti Amjad Ali Azmi
Bahare Shariat Jild 3 By SadurshSharia Mufti Amjad Ali AzmiBahare Shariat Jild 3 By SadurshSharia Mufti Amjad Ali Azmi
Bahare Shariat Jild 3 By SadurshSharia Mufti Amjad Ali Azmi
 
Bahare Shariat Jild 5 By SadurshSharia Mufti Amjad Ali Azmi
Bahare Shariat Jild 5 By SadurshSharia Mufti Amjad Ali AzmiBahare Shariat Jild 5 By SadurshSharia Mufti Amjad Ali Azmi
Bahare Shariat Jild 5 By SadurshSharia Mufti Amjad Ali Azmi
 
TUYỂN TẬP 20 ĐỀ THI KHẢO SÁT HỌC SINH GIỎI MÔN TIẾNG ANH LỚP 6 NĂM 2020 (CÓ Đ...
TUYỂN TẬP 20 ĐỀ THI KHẢO SÁT HỌC SINH GIỎI MÔN TIẾNG ANH LỚP 6 NĂM 2020 (CÓ Đ...TUYỂN TẬP 20 ĐỀ THI KHẢO SÁT HỌC SINH GIỎI MÔN TIẾNG ANH LỚP 6 NĂM 2020 (CÓ Đ...
TUYỂN TẬP 20 ĐỀ THI KHẢO SÁT HỌC SINH GIỎI MÔN TIẾNG ANH LỚP 6 NĂM 2020 (CÓ Đ...
 
Bahare Shariat Jild 1 By SadurshSharia Mufti Amjad Ali Azmi
Bahare Shariat Jild 1 By SadurshSharia Mufti Amjad Ali AzmiBahare Shariat Jild 1 By SadurshSharia Mufti Amjad Ali Azmi
Bahare Shariat Jild 1 By SadurshSharia Mufti Amjad Ali Azmi
 
مختصر علم احكام القرآن فقه القرآن وفق منهج العرض
مختصر علم احكام القرآن فقه القرآن وفق منهج العرضمختصر علم احكام القرآن فقه القرآن وفق منهج العرض
مختصر علم احكام القرآن فقه القرآن وفق منهج العرض
 
LAR MARIA MÃE DE ÁFRICA .
LAR MARIA MÃE DE ÁFRICA                 .LAR MARIA MÃE DE ÁFRICA                 .
LAR MARIA MÃE DE ÁFRICA .
 

Empfohlen

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Empfohlen (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Core Data

  • 1. Core Data iz iPhone vidika Matej Bukovinski www.bukovinski.com sreda, 16. december 2009
  • 2. Agenda • Malo teorije (z kodo) • Malo prakse (preprost Xcode demo) • Q&A sreda, 16. december 2009
  • 3. Core Data 1. del, Teorija sreda, 16. december 2009
  • 4. Core data • Mehanizmi za upravljaje z objektnim grafom in življenjskim ciklom objektov • Zagotavlja trajnost podatkov (presistence) • Enostavnejši način za ravnanje z MVC Model objekti • Framework (CoreData.framework) • Sestavni del Cocoa API-ja od Mac OS X 10.4 • Sestavni del Cocoa-touch od iPhone OS 3.0 sreda, 16. december 2009
  • 5. Prednosti • Model objekte preprosto narišemo (z relacijami!) v entitetnem modelu (včasih popolnoma brez kode) • Znebimo se ogromno kode za zagotavljanje trajnosti podatkov (nalaganje, shranjevanje,...) • Učinkovitost (hitrejše in pogosto manj pomnilniško zahtevno kot direktni SQL pristop) • Priročne metode za poizvedovanje in optimizacijo • Faulting (povezani objekt se po potrebi samodejno naloži) • Undo manager sreda, 16. december 2009
  • 6. Slabosti • Nekateri (Aaron) imajo rajši popolni nadzor nad tem kaj se dogaja z objekti v ozadju sreda, 16. december 2009
  • 7. Core Data sklad NSManagedObjectContext NSManagedObject NSManagedObject NSManagedObject NSManagedObject NSPresistentStoreCoordinator Entitetni model NSPresistentStore Podatkovna shramba (npr. SQLite) sreda, 16. december 2009
  • 8. Core Data sklad NSManagedObjectContext NSManagedObject NSManagedObject NSManagedObject NSManagedObject NSPresistentStoreCoordinator Entitetni model NSPresistentStore Podatkovna shramba (SQL, ...) sreda, 16. december 2009
  • 9. Core Data, uporaba v praksi 1 2 NSManagedObjectContext NSManagedObject NSManagedObject NSManagedObject NSManagedObject Entitetni model + NSFetchRequest • Narišemo (ali spišemo) entitetni • Nad NSManagedObjectContext izvajamo splošne model, ki predstavlja naše poslovne operacije (shranjevanje, nalaganje, dodajanje modelnih objekte objektov) • Tu določimo entitete, razmerja med • Poizvedbe oblikujemo z NSFechRequest (podobno kot njimi entitetami, atibute, omejitve... SQL) • Po potrebi generiramo izvorno kodo v • Entitete so predstavljene z objekti, ki dedujejo od kateri lahko dodajamo dodatno logiko NSManagedObject, z njimi ravnamo kot z običajnimi modelnim objektov Objective-C objekti sreda, 16. december 2009
  • 10. Inicializacija 1. Naložimo entitetni model (NSManagedObjectModel) 2. Ustvarimo koordinatorja (NSPresistentStore- Coordinator) in ga povežemo z modelom 3. Dodamo shrambo (NSPresistentStore) 4. Ustvarimo kontekst (NSManagedObjectContext) in ga povežemo s koordinatorjem sreda, 16. december 2009
  • 11. Inicializacija 1. Naložimo entitetni model (NSManagedObjectModel) 2. Ustvarimo koordinatorja (NSPresistentStore- Coordinator) in ga povežemo z modelom 3. Dodamo shrambo (NSPresistentStore) 4. Ustvarimo kontekst (NSManagedObjectContext) in ga povežemo s koordinatorjem Če izberemo pravi Xcode template je to za nas že poskrbljeno! sreda, 16. december 2009
  • 12. Nalaganje iz shrambe // Ustvarimo fetch request (poizvedba) NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init] autorelease]; // Povemo katera entiteta nas zanima NSEntityDescription *entity = [NSEntityDescription entityForName:@"Song" inManagedObjectContext:self.managedObjectContext]; [fetchRequest setEntity:entity]; // Povemo kako želimo sortirati (opcijsko) NSSortDescriptor *sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES] autorelease]; NSArray *sortDescriptors = [[NSArray arraytWithObjects:sortDescriptor, nil]; [fetchRequest setSortDescriptors:sortDescriptors]; // Naredimo poizvedbo in s tem ustvarimo naše objekte NSError *error; NSArray *songs = [managedObjectContext executeFetchRequest:request error:&error]; sreda, 16. december 2009
  • 13. Nalaganje iz shrambe // Ustvarimo fetch request (poizvedba) NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init] autorelease]; // Povemo katera entiteta nas zanima NSEntityDescription *entity = [NSEntityDescription entityForName:@"Song" inManagedObjectContext:self.managedObjectContext]; [fetchRequest setEntity:entity]; // Povemo kako želimo sortirati (opcijsko) NSSortDescriptor *sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES] autorelease]; NSArray *sortDescriptors = [[NSArray arraytWithObjects:sortDescriptor, nil]; [fetchRequest setSortDescriptors:sortDescriptors]; // Naredimo poizvedbo in s tem ustvarimo naše objekte NSError *error; NSArray *songs = [managedObjectContext executeFetchRequest:request error:&error]; sreda, 16. december 2009
  • 14. Nalaganje iz shrambe // Ustvarimo fetch request (poizvedba) NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init] autorelease]; // Povemo katera entiteta nas zanima NSEntityDescription *entity = [NSEntityDescription entityForName:@"Song" inManagedObjectContext:self.managedObjectContext]; [fetchRequest setEntity:entity]; // Povemo kako želimo sortirati (opcijsko) NSSortDescriptor *sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES] autorelease]; NSArray *sortDescriptors = [[NSArray arraytWithObjects:sortDescriptor, nil]; [fetchRequest setSortDescriptors:sortDescriptors]; // Naredimo poizvedbo in s tem ustvarimo naše objekte NSError *error; NSArray *songs = [managedObjectContext executeFetchRequest:request error:&error]; sreda, 16. december 2009
  • 15. Nalaganje iz shrambe // Ustvarimo fetch request (poizvedba) NSFetchRequest *fetchRequest = [[[NSFetchRequest alloc] init] autorelease]; // Povemo katera entiteta nas zanima NSEntityDescription *entity = [NSEntityDescription entityForName:@"Song" inManagedObjectContext:self.managedObjectContext]; [fetchRequest setEntity:entity]; // Povemo kako želimo sortirati (opcijsko) NSSortDescriptor *sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES] autorelease]; NSArray *sortDescriptors = [[NSArray arraytWithObjects:sortDescriptor, nil]; [fetchRequest setSortDescriptors:sortDescriptors]; // Naredimo poizvedbo in s tem ustvarimo naše objekte NSError *error; NSArray *songs = [managedObjectContext executeFetchRequest:request error:&error]; sreda, 16. december 2009
  • 16. Shranjevanje sprememb NSError *error; // Če ni sprememb ni potrebno shranjevati if ([managedObjectContext hasChanges]) { $ // Shranjevanje vseh sprememb - 1 vrstica kode! $ if (![managedObjectContext save:&error]) { $ $ // Poskrbi za napako $ } } sreda, 16. december 2009
  • 17. Shranjevanje sprememb NSError *error; // Če ni sprememb ni potrebno shranjevati if ([managedObjectContext hasChanges]) { $ // Shranjevanje vseh sprememb - 1 vrstica kode! $ if (![managedObjectContext save:&error]) { $ $ // Poskrbi za napako $ } } sreda, 16. december 2009
  • 18. Dodajanje novih objektov // Ponavadi uporabljamo NSEntityDescription za ustvarjanje novih entitet Song *newSong = [NSEntityDescription $ $ $ $ $ insertNewObjectForEntityForName:@"Song" $ $ $ $ $ inManagedObjectContext:self.managedObjectContext]; // Sedaj imamo Objective-C objekt, ki je umeščen v kontekst // Z njim ravnamo kot z vsemi drugimi objekti newSong.title = @"Yellow Submarine"; sreda, 16. december 2009
  • 19. Dodajanje novih objektov // Ponavadi uporabljamo NSEntityDescription za ustvarjanje novih entitet Song *newSong = [NSEntityDescription $ $ $ $ $ insertNewObjectForEntityForName:@"Song" $ $ $ $ $ inManagedObjectContext:self.managedObjectContext]; // Sedaj imamo Objective-C objekt, ki je umeščen v kontekst // Z njim ravnamo kot z vsemi drugimi objekti newSong.title = @"Yellow Submarine"; sreda, 16. december 2009
  • 20. Brisanje objektov // Samo podamo konkretno “Song” instanco [self.managedObjectContext deleteObject:song]; sreda, 16. december 2009
  • 21. NSFetchedResultsController • Poenostavlja delo z UITableView pri uporabi Core Data • Podamo NSFetchRequest, način sortiranja in grupiranja • V UITableViewDataSource metodah kličemo metode na NSFetchedResultsContoller-ju in dobimo potrebne podatke za populacijo tabele • Učinkovito (nalaganje v skupinah, sprostitev nevidnih objektov, uporaba predpomnjenja) sreda, 16. december 2009
  • 22. NSFetchedResultsController inicializacija // Pred tem ustrezno pripravimo fetchRequest self.fetchController = [[[NSFetchedResultsController alloc] $ $ $ $ $ $ initWithFetchRequest:fetchRequest $ $ $ $ $ $ managedObjectContext:self.managedObjectContext $ $ $ $ $ $ sectionNameKeyPath:@"artist" $ $ $ $ $ $ cacheName:@"songsCache"] autorelease]; NSError *error; BOOL success = [self.fetchController performFetch:&error]; if (!success) { $ // Napaka.. } sreda, 16. december 2009
  • 23. NSFetchedResultsController inicializacija // Pred tem ustrezno pripravimo fetchRequest self.fetchController = [[[NSFetchedResultsController alloc] $ $ $ $ $ $ initWithFetchRequest:fetchRequest $ $ $ $ $ $ managedObjectContext:self.managedObjectContext $ $ $ $ $ $ sectionNameKeyPath:@"artist" $ $ $ $ $ $ cacheName:@"songsCache"] autorelease]; NSError *error; BOOL success = [self.fetchController performFetch:&error]; if (!success) { $ // Napaka.. } sreda, 16. december 2009
  • 24. NSFetchedResultsController uporaba (1 od 2) - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { $ // Hrošč pri 3.0, glej NSFetchedResultsController dokumentacijo, 3.1 OK $ return [[self.fetchController sections] count]; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection: (NSInteger)section { $ id <NSFetchedResultsSectionInfo> sectionInfo = $ $ $ [[fetchController sections] objectAtIndex:section]; $ return [sectionInfo numberOfObjects]; } - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection: (NSInteger)section { $ $ id <NSFetchedResultsSectionInfo> sectionInfo = $ $ $ [[fetchController sections] objectAtIndex:section]; return [sectionInfo name]; } sreda, 16. december 2009
  • 25. NSFetchedResultsController uporaba (1 od 2) - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { $ // Hrošč pri 3.0, glej NSFetchedResultsController dokumentacijo, 3.1 OK $ return [[self.fetchController sections] count]; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection: (NSInteger)section { $ id <NSFetchedResultsSectionInfo> sectionInfo = $ $ $ [[fetchController sections] objectAtIndex:section]; $ return [sectionInfo numberOfObjects]; } - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection: (NSInteger)section { $ $ id <NSFetchedResultsSectionInfo> sectionInfo = $ $ $ [[fetchController sections] objectAtIndex:section]; return [sectionInfo name]; } sreda, 16. december 2009
  • 26. NSFetchedResultsController uporaba (1 od 2) - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { $ // Hrošč pri 3.0, glej NSFetchedResultsController dokumentacijo, 3.1 OK $ return [[self.fetchController sections] count]; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection: (NSInteger)section { $ id <NSFetchedResultsSectionInfo> sectionInfo = $ $ $ [[fetchController sections] objectAtIndex:section]; $ return [sectionInfo numberOfObjects]; } - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection: (NSInteger)section { $ $ id <NSFetchedResultsSectionInfo> sectionInfo = $ $ $ [[fetchController sections] objectAtIndex:section]; return [sectionInfo name]; } sreda, 16. december 2009
  • 27. NSFetchedResultsController uporaba (2 od 2) - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { $ static NSString *CellIdentifier = @"SongCell"; $ UITableViewCell *cell = [tableView $ $ $ dequeueReusableCellWithIdentifier:CellIdentifier]; $ if (cell == nil) { $ $ cell = [[[UITableViewCell alloc] $ $ $ $ initWithStyle:UITableViewCellStyleSubtitle $ $ $ $ reuseIdentifier:CellIdentifier] autorelease]; $ } $ Song *song = (Song *)[fetchController objectAtIndexPath:indexPath]; $ cell.textLabel.text = song.title; $ cell.detailTextLabel.text = song.genre; $ return cell; } sreda, 16. december 2009
  • 28. Core Data 2. del, Praksa - demo time sreda, 16. december 2009
  • 29. Core Data 3. del, Q&A sreda, 16. december 2009