Latest 0.0.9
Homepage https://github.com/MadAppGang/MAGCoreData
License MIT
Platforms ios 7.0, requires ARC
Dependencies ISO8601DateFormatter
Frameworks CoreData
Authors

![MAGCoreData](http://i.imgur.com/anoiYlP.png)

CocoaPods Compatible
master branch: Build Status
develop branch:Build Status

Index

What is MAGCoreData?

Core Data boilerplate code killer.

Requirement

  • iOS 7.0+
  • Xcode 6.3

Installation with CocoaPods

CocoaPods is a dependency manager of Cocoa projects, which automates and simplifies the process of using 3rd-party libraries in your projects

Podfile

pod 'MAGCoreData', '~> 0.0.4'

Usage

Initialization

MAGCoreData setup:

[MAGCoreData prepareCoreData];
[MAGCoreData instance].autoMergeFromChildContexts = YES;

You can also use one of the following setup calls with the MAGCoreData class to initialize:

+ (BOOL)prepareCoreDataWithModelName:(NSString *)modelName error:(NSError **)error;
+ (BOOL)prepareCoreDataWithModelName:(NSString *)modelName andStorageName:(NSString *)storageName error:(NSError **)error;

Managed object contexts

To access the default context you can call:

NSManagedObjectContext *defaultContext = MAGCoreData.context;

If you need to create a new managed object context for usage in non-main threads you can use the following method:

NSManagedObjectContext *privateContext = MAGCoreData.createPrivateContext;

Adding objects

To create and insert a new instance of an Entity in the default context you can use:

Weather *weather = [Weather create];
Weather *weather = [Weather createFromDictionary:dictionary];

You can also create and insert an object into specific context:

Weather *weather = [Weather createInContext:context];
Weather *weather = [Weather createFromDictionary:dictionary inContext:context];

Updating objects

To update objects you should specify primary key. See ‘Mapping’ section for additional instructions.

To update or create a new object:

Weather *weather = [Weather safeCreateOrUpdateWithDictionary:dictionary];

To update or create an object in specific context:

Weather *weather = [Weather safeCreateOrUpdateWithDictionary:dictionary inContext:context];

To update an object, change the object’s property, primary key value may be updated:

[weather safeSetValuesForKeysWithDictionary:dictionary];

Fetching objects

Weather *weather = [Weather objectForPrimaryKey:primaryKey];
Weather *weather = [Weather getOrCreateObjectForPrimaryKey:primaryKey];
Weather *weather = [Weather first];
...
NSArray *array = [Weather all];
NSArray *array = [Weather allOrderedBy:@"temperature" ascending:YES];
NSArray *array = [Weather allForPredicate:predicate orderBy:@"temperature" ascending:YES];
...

Also you can use any of these calls with specific context.

Saving objects

You probably should save data after any changes you have made, because if the application crashes you’re going to loss all the changes.

To save data:

[MAGCoreData save];

or

[MAGCoreData saveContext:context];

Deleting objects

To delete a single object in the default context:

[weatherObject delete];

To delete all objects in the default context:

[Weather deleteAll];

To delete all objects in a specific context:

[Weather deleteAllInContext:context];

Mapping

Example of usage:

#import "Weather.h"
#import "NSManagedObject+MAGCoreData.h"

@interface Weather ()
@end

@implementation Weather

+ (void)initialize {
    [self setKeyMapping:@{
                          @"identifier"  : @"id",
                          @"city"        : @"city",
                          @"temperature" : @"temperature",
                          @"updatedAt"   : @"updatedAt"
                          }];
    [self setPrimaryKeyName:@"identifier"];
    [self setUpdateDateKeyName:@"updatedAt"];
    [self setDateFormats:@{@"updatedAt":@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSS'Z'"}];
}

@end
Weather *weather = [Weather createFromDictionary:@{@"id": @"1", @"city": @"Glasgow", @"temperature": @"17"}];
NSLog(@"%@", weather.identifier); // 1
NSLog(@"%@", weather.city); // Glasgow
NSLog(@"%@", weather.temperature); // 17

Auto-mapping

The feature allows to set properties automatically if the key dictionary and the object’s property name are the same.

Student *student = [Student createFromDictionary:@{@"identifier": @"1", @"name": @"Marcus"}];
NSLog(@"id = %@", student.identifier); // 1
NSLog(@"name = %@", student.name); // Marcus

Relation classes

Example of usage:

@implementation School
+ (void)initialize {
    [self setKeyMapping:@{@"identifier": @"id", @"students": @"students"}];
    [self setPrimaryKeyName:@"identifier"];

    [self setRelationClasses:@{@"students": [Student class]}];
}
@end
@implementation Student
+ (void)initialize {
    [self setKeyMapping:@{@"identifier": @"id", @"name": @"name"}];
    [self setPrimaryKeyName:@"identifier"];
}
@end
NSDictionary *dictionary = @{@"id": @"1", @"students": @[@{@"id": @"1", @"name": @"Marcus"}, @{@"id": @"2", @"name": @"Livia"}]};
School *school = [School createFromDictionary:dictionary];
NSLog(@"First student's name is %@", ((Student *)school.students.allObjects[0]).name); // Marcus
NSLog(@"Second student's name is %@", ((Student *)school.students.allObjects[1]).name); // Livia

Value transformers

Example of usage:

+ (void)initialize {
    [self setKeyMapping:@{@"fog": @"fog"}];
    [self setValueTransformers:@{@"fog": ^id(id value) { return @(((NSString *)value).boolValue); }}];
}
Weather *weather = [Weather createFromDictionary:@{@"fog": @"YES"}];
NSLog(@"Fog = %@", weather.fog); // 1

Deleting storage

To delete all the data from the first persistent store in the persistent store coordinator:

[MAGCoreData deleteAll];

To drop the storage with a default name:

[MAGCoreData deleteAllInStorageWithName:nil];

To drop the storage with a specific name:

[MAGCoreData deleteAllInStorageWithName:storageName];

Logging

You can define Preprocessor Macros MAGCOREDATA_LOGGING_ENABLED which enable MAGCoreData logging.

Mogenerator

We recommend you to use mogenerator. Mogenerator generates the model classes from Core Data model (.xcdatamodel) and adds helper functions for your classes to simplify their usage.

Mogenerator script example:

mogenerator -m "${PROJECT_DIR}/MAGCoreDataExample/Models/Model.xcdatamodeld/Model.xcdatamodel" -M "${PROJECT_DIR}/MAGCoreDataExample/Models/MachineModel" -H "${PROJECT_DIR}/MAGCoreDataExample/Models/HumanModel" --template-var arc=true

Credits

MAGCoreData is owned and maintained by the MadAppGang.

License

MAGCoreData is released under the MIT license. See LICENSE for details.

Latest podspec

{
    "name": "MAGCoreData",
    "version": "0.0.9",
    "summary": "CoreData classes helpers from MadAppGang.",
    "description": "MAGCoreData is Core Data helpers classes to kill boilerplate code.nn* Easy creating of managed object context, and child contextesn* Helping to parse NSDictionary to NSManagedObject with easy class mappingn* Category for NSManagedObjectContext for easy objects management (find, update, create)n* Fetch Result controller class for helping data refreshing when data is updated",
    "homepage": "https://github.com/MadAppGang/MAGCoreData",
    "license": "MIT",
    "authors": {
        "Ievgen Rudenko": "[email protected]"
    },
    "platforms": {
        "ios": "7.0"
    },
    "source": {
        "git": "https://github.com/MadAppGang/MAGCoreData.git",
        "tag": "0.0.9"
    },
    "source_files": [
        "MagCoreData",
        "MagCoreData/**/*.{h,m}"
    ],
    "frameworks": "CoreData",
    "requires_arc": true,
    "dependencies": {
        "ISO8601DateFormatter": [
            "~> 0.7.0"
        ]
    }
}

Pin It on Pinterest

Share This