在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):editfmah/sharkorm开源软件地址(OpenSource Url):https://github.com/editfmah/sharkorm开源编程语言(OpenSource Language):C 92.9%开源软件介绍(OpenSource Introduction):Shark ORMShark allows you to create a model layer in your iOS, macOS or tvOS app naturally, using simple and clean syntax. Shark does as much of the heavy lifting for you, so you don't have to put unnecessary effort into dealing with your data objects. Its mantra is simple, to be fast, simple and the first choice for any developer. Getting startedShark is designed to get your app working quickly, integrated as source code, or as a framework. RequirementsXCode 9+, iOS8+ Install From CocoapodsTo install it, simply add the following line to your Podfile:pod "SharkORM" Install as FrameworkDownload the source code from the GitHub release, and then within your application, add the following: import SharkORM Install as SourceDownload the source code from GitHub and add to your target the contents of Core and SQLite, then add Getting help and supportIf you are having trouble with your implementation then simply ask a question on Stack Overflow, the team actively monitor SO and will answer your questions as quickly as possible. If you have found a bug or want to suggest a feature, then feel free to use the issue tracker in GitHub (https://github.com/sharksync/sharkorm/issues) to raise an issue. UsageSetting up your projectOnce you have added the SharkORM framework into your application, you will need to start it as soon as possible in your application lifecycle. SRKDelegate needs to be set as well, we recommend this is added to your application delegate. // Swift
class AppDelegate: UIResponder, UIApplicationDelegate, SRKDelegate Then you need to start SharkORM early on: // Swift
SharkORM.setDelegate(self)
SharkORM.openDatabaseNamed("MyDatabase") ObjectsSharkORM objects are normal classes with properties defined on them, the ORM then inspects all these classes and mirrors their structure in a SQLite database automatically. If you add or remove columns, then the tables are updated to represent the current structure of the classes. You can use these classes in much the same way as any other class in the system, and they can be extended with methods and sub classed, and passed around from thread to thread with no problem. Much like other ORM's, Swift & Objective-C entities have to have their properties defined as dynamic to allow the ORM to install it's own methods for get/set. // Swift
class Person: SRKObject {
@objc dynamic var name: String?
@objc dynamic var age: Int = 0
@objc dynamic var height: Float = 0
// add a one->many relationship from the Person entity to the Department entity.
@objc dynamic var department: Department?
} Schemas (Migration)The schema is automatically maintained from the class signatures and all additions, deletions & type changes are automatically made to the database. Where possible data is retained and converted between types. If a default value is specified using, Tables are created automatically by referencing a class which is a subclass of SRKObject. Excluding properties from the schema.By default all properties that are Example: // Swift
override class func ignoredProperties() -> [String] {
return ["height"]
} Example Object// Swift
class Person: SRKObject {
@objc dynamic var name: String?
@objc dynamic var age: Int = 0
@objc dynamic var payrollNumber: Int = 0
// add a one->many relationship from the Person entity to the Department entity.
@objc dynamic var department: Department?
} Initial valuesYou can initialise an SRKObject with a dictionary, allowing you to populate an object programatically. Example: // Swift
let p = Person(dictionary: ["name" : "Shark Developer", "age" : 39]) ##Supported Types Shark supports the following (Objective-c) types: Relationships
With the Person object already defined, and with a property department let’s look at the Department class.
class Department : SRKObject {
@objc dynamic var name: String?
@objc dynamic var location: Location?
} One-to-One RelationshipsThis has been created by adding the
let employee = Person()
let section = Department()
employee.department = section Properties can then be accessed directly, and Shark will automatically retrieve any related objects and allow you to access their properties. For example One-to-Many RelationshipsYou can define to-many relationships by adding methods to the inverse relationship. For example, to relate in a to-many relationship
func people() -> [Person] {
return Person.query()
.where("department = ?", parameters: [self])
.fetch() as! [Person]
} Indexing PropertiesShark supports indexing by overriding the
override class func indexDefinitionForEntity() -> SRKIndexDefinition? {
return SRKIndexDefinition(["name","age"])
} These will automatically be matched to the appropriate query to aid performance. All related object properties are automatically indexed as is required for caching. So there would be no need, for instance, to add in an index for Default ValuesYou can specify a set of default values for whenever a new override class func defaultValuesForEntity() -> [String : Any] {
return ["name" : "Billy", "age" : 36]
} TriggersShark objects all have the same methods available for them, to enforce constraints and check validity before or after writes have been made. entityWillInsert(), entityWillUpdate(), entityWillDelete() returning boolObjects receive this method before any action has been carried out. In here you can test to see if you wish the operation to continue. If
override func entityWillDelete() -> Bool {
return self.people().count == 0;
} entityDidInsert(), entityDidUpdate(), entityDidDelete()Objects receive this message after an event has happened and after the transaction is complete. Printing objects using print(), NSLog or poWe have provided a printable dictionary styled output which, when called, produces output like below.
Writing ObjectsShark looks to simplify the persistence of objects down to a simple method
// Create a new object
var thisPerson = Person()
// Set some properties
thisPerson.age = 38;
thisPerson.payrollNumber = 123456;
thisPerson.name = "Adrian Herridge";
// Persist the object into the datastore
thisPerson.commit() Objects are committed immediately and are written to the store in an atomic fashion. They will become immediately queryable upon completion. .commitOptions (property)the commitOptions property is present in all SRKObjects, and allows the developer to control on an object-by-object basis how SharkORM behaves when asked to commit certain objects. The following properties are used to control the logic and add fine grain control: postCommitBlock Called once a successful commit has completed postRemoveBlock Called after an object has been removed from the data store ignoreEntities Allows the developer to specify an array of child/related entities that will not be persisted when the parent object is commited. commitChildObjects If set, then all child/related entitied will not automatically be commited too. resetOptionsAfterCommit If set, then all defaults will be restored and all blocks cleared. raiseErrors If set to false then any errors generated are ignored and not raised with the delegate. Transactions will also not be failed. triggerEvents If set to true then events are raised for insert,update,delete operations. Writing in TransactionsFor some batch storage situations, it may be better to batch a lot of writes into a single transaction, this will improve speed, and give you atomicity over the persistence to the data store. All changes to all objects will be rolled back upon any raised error within the block. Event triggers will be not be executed until successful completion of the transaction. You may manually fail a transaction by calling
SRKTransaction.transaction({
// Create a new object
var thisPerson = Person()
thisPerson.name = "Adrian Herridge";
thisPerson.commit()
}) {
// the rollback on failure
} QueryingTo retrieve objects back, we use the SRKQuery object that is associated with every The final call to a query object is made using An example to fetch an entire table:
var results : SRKResultSet = Person.query().fetch() Queries can be built up using a FLUENT interface, so every call except a call to a retrieval method returns itself as a var results = Person.query()
.where("age = ?", parameters: [35])
.limit(99)
.order("name")
.fetch() you can also use object dot notation to query related objects via the property path. If we take the example of a Person class which is related to the Department class via the
Person.query().where("department.name = ?", parameters: ["Test Department"]).fetch() Where
Supported parameters to |