Wednesday, April 3, 2013

Core Data Relationship and Relationship Delete Rules

If your data model is complex,you could need to set Core Data Relationship,

Take my App "FrozenTime" for example,It need to set two entity(Album and Photo).

Album and Photo is One-to-Many Relationships.

The red rectangle area is the "One-to-Many Relationships" look like.

We also need to set each album and photo in Utilities tab.

Before we do that,you should read Relationship Delete Rules from Apple document.

Relationship Delete Rules
A relationship's delete rule specifies what should happen if an attempt is made to delete the source object. Note the phrasing in the previous sentence—"if an attempt is made…". If a relationship's delete rule is set to Deny, it is possible that the source object will not be deleted. Consider again a department's employees relationship, and the effect that the different delete rules have.

If there is at least one object at the relationship destination, then the source object cannot be deleted.
For example, if you want to remove a department, you must ensure that all the employees in that department are first transferred elsewhere (or fired!) otherwise the department cannot be deleted.

Set the inverse relationship for objects at the destination to null.
For example, if you delete a department, set the department for all the current members to null. This only makes sense if the department relationship for an employee is optional, or if you ensure that you set a new department for each of the employees before the next save operation.

Delete the objects at the destination of the relationship.
For example, if you delete a department, fire all the employees in that department at the same time.

No Action
Do nothing to the object at the destination of the relationship.
For example, if you delete a department, leave all the employees as they are, even if they still believe they belong to that department.


Set Album and Photo entity

Click Photo entity relationships tag "album",set it as below pic.

Click Album entity relationships tag "photos",set it as below pic.

Save Album and Photo Entity
//Image File Name
NSString *ImageFileName=[NSString stringWithFormat:@"%04i",receiveIndex];
//Create Photo Entity
Photo *currentPhoto=[[Photo alloc]
                     initWithEntity:[NSEntityDescription entityForName:@"Photo" inManagedObjectContext:self.managedObjectContext]  
//Set Current Photo
[currentPhoto setIndex:[NSNumber numberWithInt:0]];

[currentPhoto setName:ImageFileName];
NSString *projectFolder=[NSString stringWithFormat:@"%d", albumIndex];
NSString *saveProjectPath=[HanpoFileHelper creatFolder:projectFolder];
[currentPhoto setPath:saveProjectPath];
//Add Current Photo to Current Album 
[currentAlbum addPhotosObject:currentPhoto];
//Set Number of Sheets to Current Album
[currentAlbum setSheets:[NSNumber numberWithInteger:sheets]];
//Save File to Core Data
NSError *savingError;
if (![self.managedObjectContext save:&savingError])NSLog(@"Error saving: %@", savingError);

Load from Core Data and Get Image
//Get Core Data(TableView didSelectRowAtIndexPath)
NSManagedObject *object = [self.fetchedResultsController objectAtIndexPath:indexPath];
Album *album=(Album*)object;
//Get All Photos Entity
NSArray *photosArray=[ allObjects];
//Sort Photo Entity by Name
NSSortDescriptor *nameDescriptor =[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
NSArray * descriptors =[NSArray arrayWithObjects:nameDescriptor, nil];
NSArray *sortedPhotoArray=[photosArray sortedArrayUsingDescriptors:descriptors];
NSInteger countSortedPhotoArray=[sortedPhotoArray count];

//Put Image into array or do other things
NSMutableArray *imgArray=[[NSMutableArray alloc]init];
int i;
for (i=0; i<countSortedPhotoArray; i++) {
    Photo *tempPhoto=[sortedPhotoArray objectAtIndex:i];
    NSString *;
    NSString *path=tempPhoto.path;
    NSString *fileName=[name stringByAppendingString:@".jpg"];
    NSString *fullPath=[path stringByAppendingPathComponent:fileName];
    UIImage *image=[UIImage imageWithContentsOfFile:fullPath];
    [imgArray addObject:image];

Delete Album and Photo
In tableview method

- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
newIndexPath:(NSIndexPath *)newIndexPath

To delete album and photos just need to write this.
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
If you set right delete rule in your entity(Here's Cascade).

When you delete album,all photos in that album will also delete.


  1. Replies
    1. Great Article Image Processing Projects Deep Learning Projects for Final Year JavaScript Training in Chennai JavaScript Training in Chennai The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training Project Centers in Chennai

  2. is barred except under very specific circumstances from releasing the information of that test. However, the employer can release this information to governmental agencies or courts without requiring a court order

  3. This comment has been removed by the author.

  4. Can I just say what a relief to find someone who actually knows what they’re talking about on the internet? You definitely know how to bring an issue to light and make it important. More people need to read this and understand this side of the story. I can’t believe you’re not more popular because you definitely have the gift.

  5. Quickly drawn by essayist's restrictive method for composing.
    hero instinct phrases

  6. Aspiring to become an amazing blog writer like the writer of this blog.
    date sugar daddy

  7. Each person before your get-together has made strategies for knowledge of life, religious feelings, moral standards, etc. hero instinct

  8. Be that as it may, one viewpoint ought to be clear after you have made a decision superficially the genuine idea of your planned date you ought to uncover the person in question, your character whence you choose to meet, or prior, if adequate certainty building has occurred.

  9. it was a wonderful chance to visit this kind of site and I am happy to know. thank you so much for giving us a chance to have this opportunity.. como conquistar um homem

  10. Relationship Management deals with the treatment and management of partnerships, connections, linkages and chains between business entities.Relationship Advice

  11. In the event that you have ever thought like a web sentiment simply isn't not kidding, you are not the only one. threesome sites

  12. The thought isn't to become like one another. The thought is to permit every person to be the most grounded, most beneficial, most adjusted individual they can be. best sites for threesome

  13. I recommend iDealshare VideoGo as the most professional audio converter and video converter.

  14. This is what we call soothing and The blog is like a portal of feelings.trans dating online

  15. Fortunately we have written the authoritative reviews of top 6 cuckold dating sites for cuckold singlesbest sexting sites

  16. Unicorn Dating Site is designed specifically for bisexual couples and single unicorns. how to find a unicorn

  17. This is one of the millions and billions of reasons while individuals are having relationship issues. best threesome sites

  18. Thank you for your blog post. Much thanks again. Really Cool.
    Love Tips for Couples