Core Data Using Swift 3

User Data Model

user_data_model

Product Data Model

product_data_model

Data Model Structure

model_structure

Core Data Stack

core_data_stack

Core Data Saving Support

core_data_saving_support

Get Context To Work On Core Data Stack

persistance_store_context

Save Single Record

save_single_record

 Save Context To Update Database

save_context_for_update_database

Fetch Single Record

fetch_single_record

Add/Update Multiple Record (One-To-Many Relation)

save_update_multiple_records

Fetch Multiple Records (One To Many Relation)

fetch_multiple_record_one_to_many

Relations

Library Data Model

The Library entity has two attributes, name and location, both of type String. The Author entity also has two attributes, firstName and lastName, both of type String. The Book entity has three attributes, title of type String, publicationDate of type Date, and pages of type Integer 16. This is what the data model should look like in the data model graph.

figure-data-model-1

Planning Ahead

A library contains books and books are written by authors. That is the idea underlying the data model we are creating. This implies that the Author entity is tied to the Book entity. The Library and Book entities are also linked.

But this is one possible solution. We can also say that a library contains the books of authors and that authors have written books. Do you see the difference? In that scenario, the Library entity has a relationship with the Author entity, not the Bookentity.

When working with data models, it is critical to spend some time planning and thinking what the data model should look like. Once you have decided on the data model, it is often expensive to make drastic changes to it. We learn more about what that means for Core Data when we discuss migrations.

When working with data models, it is critical to spend some time planning and thinking what the data model should look like.

Relationships

To-One Relationships

A book belongs to a library. This means that we need to create a relationship that links a book to a library. Open Library.xcdatamodeld and switch to the editor’s tablestyle. Select the Book entity and click the plus button at the bottom of the Relationships table to add a relationship to the entity. Set Relationship to library and Destination to the Library entity. Leave Inverse empty for now.

figure-add-to-one-relationship-1

Switch to the editor’s graph style to see the visual representation of the relationship we defined.

figure-add-to-one-relationship-2

Before we move on, there are a number of details we need to discuss. The relationship we added is a to-one relationship, a book can belong to only one library. This is visualized in the data model graph by the single arrow pointing from the Bookentity to the Library entity.

Note that the arrow points from Book to Library. There is no arrow pointing back from Library to Book. There is no inverse relationship because we haven’t defined one yet. This implies that the library the book belongs to does not know that the book belongs to the library. That is not what we want, though. A library should know what books it contains. Right?

Inverse Relationships

Switch to the editor’s table style and select the Library entity. Add a relationship and name it books, plural. Set Destination to Book and set Inverse to library. By setting the inverse relationship to library, the inverse relationship of the books relationship is automatically set to the library relationship of the Book entity.

figure-add-inverse-relationship-1

Switch to the data model graph to see what that looks like. The connection between Library and Book contains arrows pointing to and from each entity.

figure-add-inverse-relationship-2

Switch back to the editor’s table style and select the Book entity. Note that the inverse relationship of the library relationship is automatically set to books because we set the inverse relationship of the books relationship to library. Core Data is clever enough to take care of that for us.

To-Many Relationships

Both library and books are to-one relationships. This severely limits the data model. A library with only one book isn’t much of a library. It is time to fix that. Select the books relationship of the Library entity in the editor’s table style. Open the Data Model Inspector in the Utilities pane on the right to see the details of the relationship.

In the Data Model Inspector, you can modify the relationship’s destination and inverse relationship. You can also modify the relationship’s type or cardinality. Core Data supports To-One and To-Many relationships. Set Type to To-Many.

figure-add-to-many-relationship-1

Switch back to the data model graph to see what has changed. The relationship from Library to Book now has two arrows, indicating that books is a to-many relationship.

figure-add-to-many-relationship-2

Many-To-Many Relationships

Wait a second. Can a book only be in one library? That may be true for an exceptionally rare book. We need to turn the library relationship into a to-manyrelationship. Select the library relationship of the Book entity in the editor’s table style and set Type to To-Many in the Data Model Inspector.

Naming conventions are very important, especially if you are working in a team. Even though the library relationship is now a to-many relationship, the name of the relationship doesn’t reflect this change. Update the name of the relationship to libraries. That makes more sense. Developers new to the project will immediately understand that a book can belong to multiple libraries.

This is what the data model graph looks like after the changes. The relationship that links the Library and Book entities is now a many-to-many relationship.

figure-add-many-to-many-relationship-1

Delete Rules

Core Data is much more than a database and this becomes clear when working with relationships. Relationships in Core Data are powerful because the framework does a lot of the heavy lifting for you.

Delete rules are one of the conveniences that make working with Core Data great. Every relationship has a delete rule. It defines what happens when the record that owns the relationship is deleted. Let me explain what that means.

Select the books relationship of the Library entity and open the Data Model Inspector on the right. By default, the delete rule of a relationship is set to nullify. Core Data supports four delete rules:

  • No Action
  • Nullify
  • Cascade
  • Deny

No Action

If the delete rule of a relationship is set to No Action, nothing happens. Let me illustrate this with an example. We have a library record that contains several book records. If the library record is deleted, the book records are not notified of this event. Every book record thinks it is still associated with the deleted library.

I have never had a need to use this delete rule. In most situations, you want to take some action when a record is deleted. That is where the other delete rules come into play.

Nullify

If the delete rule of a relationship is set to Nullify, the destination of the relationship is nullified when the record is deleted. If a library has several books and the library is deleted, the relationship pointing from the books to the library is nullified. This is the default delete rule and the delete rule you will find yourself using most often.

Cascade

Cascade is useful if the data model includes one or more dependencies. For example, if an account record has a relationship to one or more user records, it may be desirable to delete every user if the account the user belongs to is deleted. In other words, the deletion of the account record cascades to the user records it is linked to.

If you are dealing with a many-to-many relationship, though, this is often not what you want. If a library with several books is deleted, you don’t want to delete every book in the library. The books could be associated with other libraries, for example.

Deny

Deny is another powerful and useful pattern. It is the opposite of the Cascade delete rule. Instead of cascading the deletion of a record, it prevents the deletion of a record. For example, if an account is associated with several users, the account can only be deleted if it is no longer tied to any users. This configuration prevents the scenario in which users are no longer associated with an account.

Core Data Using Swift 3

Combining Two Images With CIFilter(CISourceOverCompositing)

- (void)generateSampleImage {
CIImage *background = [CIImage imageWithContentsOfURL:
                       [[NSBundle mainBundle] URLForResource:@"background" withExtension:@"png"]];
CIImage *foreground = [CIImage imageWithContentsOfURL:
                       [[NSBundle mainBundle] URLForResource:@"foreground" withExtension:@"png"]];




CIFilter *filter = [CIFilter filterWithName:@"CISourceOverCompositing"];
[filter setValue:background forKey:kCIInputBackgroundImageKey];
[filter setValue:foreground forKey:kCIInputImageKey];
CIImage *outputImage = [filter outputImage];
self.imageView.image = [self imageWithCIImage:outputImage];




NSURL *baseUrl = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory
                                                         inDomains:NSUserDomainMask] objectAtIndex:0];
NSURL *outputUrl = [baseUrl URLByAppendingPathComponent:@"output_image.png"];
[UIImagePNGRepresentation(self.imageView.image) writeToFile:outputUrl.path atomically:YES];
}
Combining Two Images With CIFilter(CISourceOverCompositing)

Apply CIFilter To An Image Using Swift

override func viewDidLoad() {
    guard let image = imageView?.image, cgimg = image.CGImage else {
        print(“imageView doesn’t have an image!”)
        return
    }
    
    let coreImage = CIImage(CGImage: cgimg)
    
    let filter = CIFilter(name: “CISepiaTone”)
    filter?.setValue(coreImage, forKey: kCIInputImageKey)
    filter?.setValue(0.5, forKey: kCIInputIntensityKey)
    
    if let output = filter?.valueForKey(kCIOutputImageKey) as? CIImage {
        let filteredImage = UIImage(CIImage: output)
        imageView?.image = filteredImage
    }
        
    else {
        print(“image filtering failed”)
    }
}
Apply CIFilter To An Image Using Swift

Add Circle CALayer Inside A View Using Core Graphics iOS (Xamarin.iOS & Objective-C)

Xamarin.iOS

public CALayer createImage(UIColor fillerColor, UIColor borderColor, UIView view, nfloat x, nfloat y)
        {
            // Get the size
            CGSize canvasSize = view.Frame.Size;
            nfloat scale = UIScreen.MainScreen.Scale;

            // Resize for retina with the scale factor
            canvasSize.Width *= scale;
            canvasSize.Height *= scale;

            // Create the context

            UIGraphics.BeginImageContext(canvasSize);
            CGContext ctx = UIGraphics.GetCurrentContext();

            // setup drawing attributes
            ctx.SetLineWidth(0.5f * scale);
            ctx.SetStrokeColor(borderColor.CGColor);
            ctx.SetFillColor(fillerColor.CGColor);

            // setup the circle size
            CGRect circleRect = new CGRect(0, 0, canvasSize.Width, canvasSize.Height);
            circleRect = circleRect.Inset(0.5f,0.5f);

            // Draw the Circle
            ctx.FillEllipseInRect(circleRect);
            ctx.StrokeEllipseInRect(circleRect);

            // Create Image
            UIImage retImage = UIGraphics.GetImageFromCurrentImageContext();

            CALayer aLayer = new CALayer();
            CGRect startFrame = new CGRect(x, y, view.Frame.Width  (2*x), view.Frame.Height  (2 * y));
            aLayer.Contents = retImage.CGImage;
            aLayer.Frame = startFrame;

            return aLayer;
        }

USE: createImage(UIColor.White, UIColor.Black, cell.ImgvEndCircle, 3f, 3f)

Objective-C

-(CALayer *)createImage:(UIColor *)fillerColor withbordercolor: (UIColor *)borderColor withView:(UIView*)view xPosition:(CGFloat)x yPosition:(CGFloat)y{

// Get the size
CGSize canvasSize = view.frame.size;
CGFloat scale = [UIScreen mainScreen].scale;

// Resize for retina with the scale factor
canvasSize.width *= scale;
canvasSize.height *= scale;

// Create the context
UIGraphicsBeginImageContext(canvasSize);
CGContextRef ctx = UIGraphicsGetCurrentContext();

// setup drawing attributes
CGContextSetLineWidth(ctx, 0.5 * scale);
CGContextSetStrokeColorWithColor(ctx, borderColor.CGColor);
CGContextSetFillColorWithColor(ctx, fillerColor.CGColor);

// setup the circle size
CGRect circleRect = CGRectMake( 0, 0, canvasSize.width, canvasSize.height );
circleRect = CGRectInset(circleRect, 0.5, 0.5);

// Draw the Circle
CGContextFillEllipseInRect(ctx, circleRect);
CGContextStrokeEllipseInRect(ctx, circleRect);

// Create Image
UIImage *retImage = UIGraphicsGetImageFromCurrentImageContext();

CALayer *aLayer = [CALayer layer];
CGRect startFrame = CGRectMake(x, y, view.frame.size.width-(2*x), view.frame.size.height-(2*y));
aLayer.contents = (id)retImage.CGImage;
aLayer.frame = startFrame;
return aLayer;
}

Add Circle CALayer Inside A View Using Core Graphics iOS (Xamarin.iOS & Objective-C)