ios : memory file operator bool crash - ios

I am using realmswift in my project, so as per apple guidelines I converted whole project into swift 4.2 and all pod libraries into latest version. Project is converted successfully but I get crash everytime when I run project.
I have uploaded screenshot for better understanding.
Now here is my model for inserting value in database
class SyncProductModel: Object, Mappable {
#objc dynamic var id: String?
#objc dynamic var productType : Int = 0
#objc dynamic var name: String?
#objc dynamic var category :String?
#objc dynamic var sku : String?
#objc dynamic var baseMOQ : Double = 0.0
#objc dynamic var isActive : Bool = false
#objc dynamic var isFavourite : Bool = false
#objc dynamic var createdAt : String?
#objc dynamic var updatedAt : String?
#objc dynamic var uom : String?
#objc dynamic var productDesc : String?
#objc dynamic var retailUOM : String?
#objc dynamic var isInCart : Bool = false
var isSelecetd = false
var attachments = List<AttachmentModel>()
var inventory = List<SyncInventoryModel>()
var inventoryModel : SyncInventoryModel?
// var tags = List<tags>()
// var baseProperties = List<baseProperties>()
required convenience init?(map: Map) {
self.init()
}
override class func primaryKey() -> String? {
return "id"
}
func mapping(map: Map) {
id <- map["id"]
productType <- map["type"]
name <- map["name"]
category <- map["category"]
sku <- map["sku"]
var baseQty : Any?
baseQty <- map["baseMOQ"]
baseMOQ = Utilities.getDoubleValue(value: baseQty)
isActive <- map["isActive"]
createdAt <- map["createdAt"]
updatedAt <- map["updatedAt"]
uom <- map["uom"]
productDesc <- map["description"]
retailUOM <- map["retailUOM"]
attachments <- (map["attachments"], ListTransform<AttachmentModel>())
// tags <- (map["attachments"], ListTransform<tags>())
// baseProperties <- (map["baseProperties"], ListTransform<baseProperties>())
}
Here is my code for inserting value into db
for obj in masterProduct
{
if self.realm.isInWriteTransaction {
self.realm.add(obj, update: true)
}
else {
try! self.realm.write {
// Here My application get crashed.
self.realm.add(obj, update: true)
}
}
}
But everytime application get crashed. Please help me I stuck here.
Any help would be appreciated.

Related

Generic class 'SyncObject' requires that 'String' inherit from 'RealmSwiftObject'

I am using IceCream Library and want to achieve the following functionality.
In app delegate, I have written
syncEngine = SyncEngine(objects: [
SyncObject(type: Recipient.self, uListElementType: String.self),
SyncObject(type: SMSSchedule.self, uListElementType: Recipient.self),
SyncObject(type: Template.self),
SyncObject(type: ContactsGroup.self, uListElementType: Recipient.self)
])
where Recipient class is...
#objc class Recipient: Object {
#objc dynamic var rec_id = ""
#objc dynamic var firstName = ""
#objc dynamic var lastName = ""
var phoneNumbers = List<String>()
#objc dynamic var email = ""
#objc dynamic var colorTag = "#FFFFFFFF"
#objc dynamic var isDeleted = false // IceCream requirement
override static func primaryKey() -> String? {
return "rec_id"
}
// initialization code
}
Look at the phoneNumbers property. It is a list of string objects. However the SyncObject doesn't accept String as uListElementType. How can I solve this issue?

Separate Realm SWIFT data into lists -- and bring data back together?

So, I am a COMPLETE newbie, learning by doing real hands-on projects. I am attempting to create an app that can keep track of car parts. I'm trying to use Realm Database. In order to be organized, I'd like to keep everything separated by key bunches: "partInfo", "storeInfo", and "mechanicInfo" and then bring this back together again with the list feature of realm. Please see my code below and tell help me learn how to go about it? Thanks in advance!
I'm also trying to do MVC pattern--not sure if I did this right by separating everything out or not.
Here's my code for storeinfo.swift
import Foundation
import RealmSwift
class StoreInfo: Object {
#objc dynamic var _id = ObjectId.generate()
#objc dynamic var storeName: String = ""
#objc dynamic var storeNumber: String? = ""
#objc dynamic var storeAddress: String = ""
var catalog = LinkingObjects(fromType: Catalog.self, property: "stores")
//var itemImgs = List<String>()
override static func primaryKey() -> String? {
return "_id"
}
}
Here's my code for partinfo.swift
import Foundation
import RealmSwift
class PartInfo: Object {
#objc dynamic var _id = ObjectId.generate()
#objc dynamic var partName: String = ""
#objc dynamic var partNumber: String = ""
#objc dynamic var partDescription: String? = ""
#objc dynamic var partCost: Double = 0.00
#objc dynamic var partQuantity: Int = 0
#objc dynamic var purchaseDate: String = ""
#objc dynamic var hasWarranty: Bool = true
#objc dynamic var warrantyLength: String? = ""
var catalog = LinkingObjects(fromType: Catalog.self, property: "parts")
//var itemImgs = List<String>()
override static func primaryKey() -> String? {
return "_id"
}
}
here's my code for mechanicinfo.swift
import Foundation
import RealmSwift
class MechanicInfo: Object {
#objc dynamic var _id = ObjectId.generate()
#objc dynamic var mechanicName: String = ""
#objc dynamic var mechanicNumber: String = ""
#objc dynamic var mechanicAddress: String? = ""
#objc dynamic var mechanicCost: Double = 0.00
#objc dynamic var serviceDate: String = ""
var catalog = LinkingObjects(fromType: Catalog.self, property: "mechanics")
//var itemImgs = List<String>()
override static func primaryKey() -> String? {
return "_id"
}
}
and finally (where I'm stuck at) -- the code for Catalog.swift
import Foundation
import RealmSwift
class Catalog: Object {
#objc dynamic var _id = ObjectId.generate()
var parts = RealmSwift.List<PartInfo>()
var stores = RealmSwift.List<StoreInfo>()
var mechanics = RealmSwift.List<MechanicInfo>()
//var itemImgs = List<String>()
override static func primaryKey() -> String? {
return "_id"
}
when I go to try to use it, I'm getting an error of already using the same name. can't use it twice: (so I had to do 3 instances of wipers, which works, but it's not what I wanted...please help!)
My ViewController:
import UIKit
import RealmSwift
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let realm = try! Realm()
print(Realm.Configuration.defaultConfiguration.fileURL!)
let wipers = PartInfo()
wipers.partName = "TRICO HD 32 Inch Wiper Blades"
wipers.partNumber = "67-324"
wipers.hasWarranty = true
wipers.warrantyLength = "2 years"
wipers.purchaseDate = "04/21/2021"
wipers.partCost = 34.99
wipers.partQuantity = 2
wipers.partDescription = "Great set. Lifespan of 6 - 9 months."
let wipers2 = StoreInfo()
wipers2.storeName = "O'Reilly AutoParts"
wipers2.storeAddress = "1003 W Broad St, Groveland, FL 34736"
wipers2.storeNumber = "4474"
let wipers3 = MechanicInfo()
wipers3.serviceDate = "04/24/2021"
wipers3.mechanicAddress = "17605 Sunshine Circle, Winter Garden, FL, 34787"
wipers3.mechanicCost = 289.58
wipers3.mechanicName = "Bob Barnicles"
wipers3.mechanicNumber = "353-256-7893"
try! realm.write {
realm.add(wipers)
realm.add(wipers2)
realm.add(wipers3)
}
}
}

Query on Inner and Outer object at same time Realm Swift

I have two objects ConversationModel and MessageModel as follows
class ConversationModel: Object, NSCoding {
#objc dynamic var conversation_id : String?
#objc dynamic var display_name : String?
#objc dynamic var to_jid : String?
#objc dynamic var from_jid : String?
#objc dynamic var unread_count : Int = 0
#objc dynamic var last_timestamp : String?
#objc dynamic var group_name : String?
#objc dynamic var group_id : String?
#objc dynamic var ghost_name : String?
#objc dynamic var ghost_password : String?
#objc dynamic var ghost_message : String?
#objc dynamic var user_profile_image : String?
#objc dynamic var last_message_status : String?
#objc dynamic var m_body : String?
#objc dynamic var sender_timestamp : String?
#objc dynamic var m_type : String?
#objc dynamic var receiver_timestamp : String?
#objc dynamic var userCustomProfileImageUrl: String?
#objc dynamic var profileImageUrl: String?
#objc dynamic var userImageHashKey: String?
#objc dynamic var userImageBase64String : String?
#objc dynamic var sender_jid : String?
#objc dynamic var reciever_jid: String?
#objc dynamic var sending_status: String?
#objc dynamic var is_blocked : Bool = false
#objc dynamic var is_business : Bool = false
#objc dynamic var is_ghost_enable : Bool = false
#objc dynamic var is_deleted : Bool = false
#objc dynamic var is_offline : Bool = false
#objc dynamic var is_archive : Bool = false
#objc dynamic var is_group : Bool = false
#objc dynamic var is_pin : Bool = false
#objc dynamic var is_mute : Bool = false
#objc dynamic var mute_time : String?
#objc dynamic var dataForImage : Data?
#objc dynamic var phoneNumber: String?
#objc dynamic var is_removed: Bool = false
#objc dynamic var audio_playedtime :String?
#objc dynamic var userThumbnailImage : String?
var messagesList = List<MessageModel>()
}
And Message Model is
class MessageModel: Object, NSCoding {
#objc dynamic var burning_msg_timestamp: String?
#objc dynamic var is_burning_msg : Int = 0
#objc dynamic var delivered_timestamp: String?
#objc dynamic var read_timestamp: String?
#objc dynamic var message_id: String?
#objc dynamic var reciever_id: String?
#objc dynamic var conversation_id: String?
#objc dynamic var body: String?
#objc dynamic var url: String?
#objc dynamic var sender_timestamp: CLong = 0
#objc dynamic var receiver_timestamp: String?
#objc dynamic var forward_tag: Int = 0
#objc dynamic var message_type: String?
#objc dynamic var stanza_id: String?
#objc dynamic var selected_message_reply_id: String?
#objc dynamic var burn_time: String?
#objc dynamic var schedule_timestamp: String?
#objc dynamic var is_scheduled: Bool = false
#objc dynamic var room_jid: String?
#objc dynamic var sender_jid: String?
#objc dynamic var is_deleted: Bool = false
}
I would like to fetch all conversation with is_archive == false and only those messageslist with is_deleted = false
I am trying to fetch with this code but its only filtering ConversationModel and not applying filter on Message Model
var result = realm.objects(ConversationModel.self).filter("is_archive = \(is_archive)
AND ANY messagesList.is_deleted == \(boolFalse) AND ANY messagesList.sender_timestamp <=
\(timeStamp)").sorted(byKeyPath: "last_timestamp", ascending: false)
I have tried Nested queries but unable to get desired result.
This isn't exactly an answer but more confirmation that your code is correct and working as intended.
To test, I copy and pasted your code and created sample data and added an _id object to ConversationModel so I could tell which was being retrieved by the query.
So we have three conversations, each having a message. The goal is for the query to retrieve conversation c1; its is_archive is false, it has a message where is_deleted is false and a sender_timestamp <= 5
let c0 = ConversationModel()
c0._id = "c0"
c0.is_archive = true
let c1 = ConversationModel()
c1._id = "c1"
c1.is_archive = false
let c2 = ConversationModel()
c2._id = "c2"
c2.is_archive = false
let m0 = MessageModel()
let m1 = MessageModel()
let m2 = MessageModel()
m0.sender_timestamp = 0
m1.sender_timestamp = 1
m2.sender_timestamp = 2
m0.is_deleted = true
m1.is_deleted = false
m2.is_deleted = true
c0.messagesList.append(m0)
c1.messagesList.append(m1)
c2.messagesList.append(m2)
try! realm.write {
realm.add([c0, c1, c2])
}
Then I ran your query, adding vars.
let is_archive = false
let boolFalse = false
let timeStamp = 5
var results = realm.objects(ConversationModel.self).filter("is_archive = \(is_archive) AND ANY messagesList.is_deleted == \(boolFalse) AND ANY messagesList.sender_timestamp <= \(timeStamp)").sorted(byKeyPath: "last_timestamp", ascending: false)
which produced this output
c1
Unfortunately you can't specify MessageMode constraints in your ConversationModel query. What you can do is create a lazy property consisting of MessageModel objects with constraints on the is_deleted and sender_timestamp properties.
class ConversationModel: Object {
// all other properties ...
var messagesList = List<MessageModel>()
lazy var activeMessages: Results<MessageModel> = {
return messagesList
.filter(.notDeleted)
.filter(.sentOnOrBefore(SOME_TIMESTAMP))
}()
override class func ignoredProperties() -> [String] {
return ["activeMessages"]
}
}
Personally, I like to organize my filter constraints like this:
extension NSPredicate {
static let notArchived = NSPredicate(format: "is_archive == false")
static let notDeleted = NSPredicate(format: "is_deleted == false")
static func sentOnOrBefore(_ timestamp: CLong) -> NSPredicate {
return NSPredicate(format: "sender_timestamp <= %d", timestamp)
}
}
extension SortDescriptor {
static let lastTimestampDescending = SortDescriptor(keyPath: "last_timestamp", ascending: false)
}
To fetch the Conversations we can do this:
func fetchConversations() throws -> Results<ConversationModel> {
let realm = try Realm()
return realm.objects(ConversationModel.self)
.filter(.notArchived)
.sorted(by: [.lastTimestampDescending])
}
Then to access the constrained messages on each conversation we can do something like this:
func processMessages(for conversations: Results<ConversationModel>) {
for conversation in conversations {
print(conversation.activeMessages)
}
}

Json parsing Issue using objectmapper library in swift

I am facing issue with parsing response from server side. I get response in this format
1.)
For first image my model class is working fine. In this I don't null
2.)
For second image response my Model class is not working it's giving nil after parsing.In this I get null in array
My Model class for my api response is this
class GetTodayMyKpiResponse: Mappable{
var status: String?
var myKpiMonth: MyKpiMonthResponse?
var myKpiWeek: MyKpiWeekResponse?
required init?(map: Map){
}
func mapping(map: Map) {
status <- map["status"]
myKpiMonth <- map["myKpiMonth"]
myKpiWeek <- map["myKpiWeek"]
}
}
class MyKpiMonthResponse: Mappable{
var myKpiMonthYear: Double?
var myKpiMonthDetailList: [MyKpiMonthDetailResponse]?
var myKpiMonthList: [MyKpiMonthListReponse]?
required init?(map: Map) {
}
func mapping(map: Map) {
myKpiMonthYear <- map["myKpiMonthYear"]
myKpiMonthDetailList <- map["myKpiMonthDetail"]
myKpiMonthList <- map["myKpiMonthList"]
}
}
class MyKpiMonthDetailResponse: Mappable{
var myKpiMonthDetailOutletCode: String?
var myKpiMonthDetailUnitTiers: [String]?
var myKpiMonthDetailTargetUnits: [String]?
var myKpiMonthDetailBonusIncentive: Double?
var myKpiMonthDetailOutletName: String?
var myKpiMonthDetailModelName: [String]?
var myKpiMonthDetailMonth: String?
var myKpiMonthDetailType: Double?
required init?(map: Map) {
}
func mapping(map: Map) {
myKpiMonthDetailOutletCode <- map["myKpiMonthDetailOutletCode"]
myKpiMonthDetailUnitTiers <- map["myKpiMonthDetailUnitTiers"]
myKpiMonthDetailTargetUnits <- map["myKpiMonthDetailTargetUnits"]
myKpiMonthDetailBonusIncentive <- map["myKpiMonthDetailBonusIncentive"]
myKpiMonthDetailOutletName <- map["myKpiMonthDetailOutletName"]
myKpiMonthDetailModelName <- map["myKpiMonthDetailModelName"]
myKpiMonthDetailMonth <- map["myKpiMonthDetailMonth"]
myKpiMonthDetailType <- map["myKpiMonthDetailType"]
}
}
class MyKpiMonthListReponse: Mappable {
var myKpiMonthMaxUnit: Double?
var myKpiMonthDate: String?
var myKpiMonthBonusAmount: Double?
var myKpiMonthActivatedUnit: Double?
var myKpiMonthMinUnit: Double?
var myKpiMonthCurrentUnit: Double?
var myKpiMonthBonusStatus: String?
var myKpiMonthOutletName: String?
var myKpiMonthOutletAddress: String?
required init?(map: Map) {
}
func mapping(map: Map) {
myKpiMonthMaxUnit <- map["myKpiMonthMaxUnit"]
myKpiMonthDate <- map["myKpiMonthDate"]
myKpiMonthBonusAmount <- map["myKpiMonthBonusAmount"]
myKpiMonthActivatedUnit <- map["myKpiMonthActivatedUnit"]
myKpiMonthMinUnit <- map["myKpiMonthMinUnit"]
myKpiMonthCurrentUnit <- map["myKpiMonthCurrentUnit"]
myKpiMonthBonusStatus <- map["myKpiMonthBonusStatus"]
myKpiMonthOutletName <- map["myKpiMonthOutletName"]
myKpiMonthOutletAddress <- map["myKpiMonthOutletAddress"]
}
}
class MyKpiWeekResponse: Mappable{
var myKpiWeekDetail: [MyKpiWeekDetailResponse]?
var myKpiWeekList: [MyKpiWeekListResponse]?
var myKpiWeekYear: Double?
var myKpiWeekMonth: Double?
required init?(map: Map) {
}
func mapping(map: Map) {
myKpiWeekDetail <- map["myKpiWeekDetail"]
myKpiWeekList <- map["myKpiWeekList"]
myKpiWeekYear <- map["myKpiWeekYear"]
myKpiWeekMonth <- map["myKpiWeekMonth"]
}
}
class MyKpiWeekDetailResponse: Mappable{
var myKpiWeekDetailEndDate: String?
var myKpiWeekDetailUnitTiers: [String]?
var myKpiWeekDetailOutletName: String?
var myKpiWeekDetailStartDate: String?
var myKpiWeekDetailType: Double?
var myKpiWeekDetailModelName: [String]?
var myKpiWeekDetailTypeOfReward: String?
var myKpiWeekDetailOutletCode: String?
var myKpiWeekDetailTargetUnits: [String]?
required init?(map: Map) {
}
func mapping(map: Map) {
myKpiWeekDetailEndDate <- map["myKpiWeekDetailEndDate"]
myKpiWeekDetailUnitTiers <- map["myKpiWeekDetailUnitTiers"]
myKpiWeekDetailOutletName <- map["myKpiWeekDetailOutletName"]
myKpiWeekDetailStartDate <- map["myKpiWeekDetailStartDate"]
myKpiWeekDetailType <- map["myKpiWeekDetailType"]
myKpiWeekDetailModelName <- map["myKpiWeekDetailModelName"]
myKpiWeekDetailTypeOfReward <- map["myKpiWeekDetailTypeOfReward"]
myKpiWeekDetailOutletCode <- map["myKpiWeekDetailOutletCode"]
myKpiWeekDetailTargetUnits <- map["myKpiWeekDetailTargetUnits"]
}
}
class MyKpiWeekListResponse: Mappable {
var myKpiWeekBonusStatus: String?
var myKpiWeekEndDate: String?
var myKpiWeekActivatedUnit: Double?
var myKpiWeekStartDate: String?
var myKpiWeekMinUnit: Double?
var myKpiWeekCurrentUnit: Double?
var myKpiWeekOutletName: String?
var myKpiWeekTypeOfReward: String?
var myKpiWeekOutletAddress: String?
var myKpiWeekMaxUnit: Double?
required init?(map: Map) {
}
func mapping(map: Map) {
myKpiWeekBonusStatus <- map["myKpiWeekBonusStatus"]
myKpiWeekEndDate <- map["myKpiWeekEndDate"]
myKpiWeekActivatedUnit <- map["myKpiWeekActivatedUnit"]
myKpiWeekStartDate <- map["myKpiWeekStartDate"]
myKpiWeekMinUnit <- map["myKpiWeekMinUnit"]
myKpiWeekCurrentUnit <- map["myKpiWeekCurrentUnit"]
myKpiWeekOutletName <- map["myKpiWeekOutletName"]
myKpiWeekTypeOfReward <- map["myKpiWeekTypeOfReward"]
myKpiWeekOutletAddress <- map["myKpiWeekOutletAddress"]
myKpiWeekMaxUnit <- map["myKpiWeekMaxUnit"]
}
}
If there is no data available then send empty array not null. Even in myKpiMonthList doesn't contain null array. There is no logic that null value in array at index 2.
You can send empty string or empty array even. Still there is no any logic for the null value.
Either handle all null value from server side else it always crash.

How to append object in Mappable class(Model). iOS swift

In my app, I'm using Alamofire-ObjectMapper.
I have a [OrderDetailSecond]. now i want to use for loop for this array and when isRxMedicine == 1 i want to add that object in any array so i can display that in my UITableView.
here is my code
this is my model
class OrderDetailSecond: Mappable {
var id : Int?
var isRxMedicine : Int?
var medicineTypeId : String?
var name : String?
var orderId : String?
var price : String?
var quentity : Int?
var strength : String?
required init?(_ map: Map){
}
func mapping(map: Map) {
id <- map["id"]
isRxMedicine <- map["is_rx_medicine"]
medicineTypeId <- map["medicine_type_id"]
name <- map["name"]
orderId <- map["order_id"]
price <- map["price"]
quentity <- map["qty"]
strength <- map["strengh"]
}
}
now here i am trying to add objects in new element
if let Rx_OrderDetail = self.orderdetailInstance, Rx_detail = Rx_OrderDetail.result{
let detailArray = Rx_detail[0].orederDetail
if let orderdata = detailArray
{
for RxDataFilter in orderdata
{
if (RxDataFilter.isRxMedicine == 1)
{
array?.append(RxDataFilter)
}
}
elementConunt = orderdata.count
}
return elementConunt
}
but its not working
Note: orderdata is in form [OrderDetailSecond]

Resources