OLCOrm is a Lightweight Object Relational Mapping (ORM) Library for iOS
- CocoaPods - For simple painless integration you need CocoaPods installed in your machine.
Basically there are two ways you can integrate this library to your project. Easy way or the Hard way ;)
CocoaPods is a dependency manager for Objective-C, which automates and simplifies the process of integrating 3rd-party libraries like OLCOrm into your projects. For more info see "Getting Started Guide". You can install it with the following command:
$ gem install cocoapods
To integrate OLCOrm into your Xcode project using CocoaPods, specify it in your Podfile
:
pod "OLCOrm"
Download and Add the library files found under OLCOrm/Pod/Classes/
into your project. In your project put the somewhere like lib/OLCOrm
To initialise your database, first import import the library's umbrella header file to your AppDelegate class as or anywhere else you want to initialize the database (recommend doing it in AppDelegate):
#import "OLCOrm.h"
Then intialize the database by calling:
OLCOrm *db = [OLCOrm databaseName:@"db-name.sqlite" version:[NSNumber numberWithInt:1] enableDebug:NO];
this command will creates the SqLite databse file for your project. Here databaseName:
let the lib know what should be the database file called. version:
sets the database version (remeber to increase this as you add/change Model classes). enableDebug:
enabling this will log all database operations in your xcode console.
For the library to work with your model classes you need to extend your Model(s) with OLCModel
class.
First import OLCModel into your model using:
#import "OLCModel.h"
Then extend like:
@interface MyModel : OLCModel
In you AppDelegate or wherever you have initialise the Database call the following to register the Model in your db:
[db makeTable:[MyCustomModel class]];
[db makeTable:[UserObject class] withMigration:NO];
registering your model like that will tell the lib to ignore migration and create an empty table
[db makeTable:[UserObject class] withTableVersion:2 withMigration:NO];
register your mode this way if you don't want to update the database version, and only update the table structure of the Model class
Following examples will guide you through on how to performe Create/Read/Update/Delete operations using the lib
To Create a table record simply call save
command on model. If the insert is successful it will return YES and NO on failure.
Example:
TestObject *test = [[TestObject alloc] init];
test.title = [NSString stringWithFormat:@"Sample Record %d", [records count]];
test.coordinates = [NSNumber numberWithDouble:234.345345];
test.currency = [NSNumber numberWithFloat:150.00];
test.flag = [NSNumber numberWithInt:1];
test.addAt = [NSDate date];
test.link = [NSURL URLWithString:@"http://google.com"];
test.status = [NSNumber numberWithInt:1];
...
return [test save];
Calling [test saveAndGetId]
will return the inserter record's Id(Primary key) while saving the data to the database. Return of -1
means failure to insert.
Call update
on your model to update the current model data. Method will return YES or NO on success or failure.
Example:
[test update];
Call delete
on your model will permanently remove the record from db. Method will return YES or NO on success or failure.
[test delete];
To retrieve all the records realted to a specific model class, call the static method all
on your model class.
Example:
NSArray *allRecords = [TestObject all];
Call static method find
on model class to find a specific record by it's primary key field.
Example:
[TestObject find:@1]
Call whereColumn:(NSString *) column byOperator:(NSString *) opt forValue:(NSString *) value accending:(BOOL) sort
static method on your model class.
Example:
[TestObject whereColumn:@"link" byOperator:@"=" forValue:@"http://google.com" accending:YES]
Example:
[TestObject where:@"flag = 1 AND link != 'enabled'" sortBy:@"title" accending:NO];
Do what ever you want... But! make sure you spell the table name right. It should be you Model Class name.
Example:
[TestObject query:@"SELECT * FROM myTable WHERE STATUS = 1"]
Ahhhhh....
[self hasOne:<Model class> foreignKey:<Foreign Key>]
Example:
[test hasOne:[UserObject class] foreignKey:@"userId"]
Or
[test belongTo:[UserObject class] foreignKey:@"userId"]
[self hasMany:<Model class> foreignKey:<Foreign Key>];
Example:
[user hasMany:[TestObject class] foreignKey:@"userId"];
For the sake of simplicity I dropped that. Well... you'll have to figure out that your self. Go away. No support here buddy.
You can specify the primary key property of and object by overiding the method + (NSString *) primaryKey
and returning the key you want, by default this is set to Id
+ (NSString *) primaryKey
{
return @"CustomPrimaryKey";
}
If you wnat properties that don't need to be saved to the database but required in runtime. No worries. Ignore thoes properties by overide the method + (NSArray *) ignoredProperties
and return an array of property names.
+ (NSArray *) ignoredProperties
{
return @[@"status", @"timer"];
}
To enable debug mode for a specific object you can overid the method + (BOOL) debug
and return YES to enable it, by default this is set to NO;
+ (BOOL) debug
{
return YES;
}
You can register for local notification on OLCOrm to monitor database changes. By registering for notifications on a specific model you can monitor Create/Update/Delete operations on that model.
To Register:
[TestObject notifyOnChanges:self withMethod:@selector(testObjNotificationListner:)];
To Unregistering:
[TestObject removeNotifyer:self];
- @ccgus for the awesome FMDB Objective-C wrapper around SQLite library.
- @kevinejohn for the neat NSObject-KJSerializer utlity class .
Everybody is welcome!
Lakitha Samarasinghe, lakitharav@gmail.com
Copyright 2015 Lakitha Samarasinghe
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
We all know the working with Core Data is major pain in the neck. Yet it is in a way bit easy you work with, if you get an hold of how it actaully work, working with only model calsses to update the database structre on the fly.
And for those who hate to use Core Data, FMDB is you best choice. But still it lack the capability of mapping objects to models. So you have to manullay create the databas and queries, ah.
So I develop this Libaray as an wrapper library to FMDB, that handle the database, table & all other CRUD function that we use daily. To make you life easire.
Happy Coding.