Skip to content

Saving a single object

This is a transaction operation responsible for saving a new object in the database. To add this operation to a Unit Of Work instance, use the following methods:

// custom class-based approach
- (OpResult *)[unitOfWorkInstance createWithTableName:(NSString * _Nonnull) objectToSave:(NSDictionary<NSString *,id> * _Nonnull)];

// map-based approach
- (OpResult *)[unitOfWorkInstance createWithObjectToSave:(id _Nonnull)];
// custom class-based approach
unitOfWorkInstance.create(tableName: String, objectToSave: [String : Any]) -> OpResult

// dictionary-based approach
unitOfWorkInstance.create(objectToSave: Any) -> OpResult

As you can see from the method signatures, there are two approaches for storing a new object in the database: class-based and map-based approaches. The former uses a class defined in your program. The signature defines that class as type Any. In this case, the name of the table where the object will be stored is the same as the name of the class. The objectToSave argument in both signatures must conform the rules defined in the Data Object section of this guide.

Return Value

The operation returns an OpResult object which represents the object stored in the database as a result of this operation. The OpResult object can be used as an argument in other operations in the same transaction (same UnitOfWork instance). It is also possible to use OpResult to "extract" the value of a property of the saved object and use it in other operations. For more information see the Operation Result chapter of this guide.

Example

Consider the following example, it demonstrates creating an object and adding it to be saved in a transaction:

@interface Person : NSObject

@property (strong, nonatomic) NSString *name;
@property NSInteger age;

@end
UnitOfWork *unitOfWork = [UnitOfWork new];

Person *person = [Person new];
person.name = @"Joe";
person.age = 25;

OpResult *addPersonResult = [unitOfWork createWithObjectToSave:person];

// add other operations
// ...

// use [unitOfWork execute] to run the transaction
@objcMembers class Person: NSObject {    
    var name: String?
    var age: Int = 0
}
let unitOfWork = UnitOfWork()

let person = Person()
person.name = "Joe"
person.age = 25

let addPersonResult = unitOfWork.create(objectToSave: person)

// add other operations
// ...

// use unitOfWork.execute() to run the transaction

UnitOfWork *unitOfWork = [UnitOfWork new];

NSDictionary *person = @{@"name": @"Joe", @"age": @25};

OpResult *addPersonResult = [unitOfWork createWithTableName:@"Person" objectToSave:person];

// add other operations
// ...

// use [unitOfWork execute] to run the transaction
let unitOfWork = UnitOfWork()

let person = ["name": "Joe", "age": 25] as [String : Any]

let addPersonResult = unitOfWork.create(tableName: "Person", objectToSave: person)

// add other operations
// ...

// use unitOfWork.execute() to run the transaction