exception 'NSInvalidArgumentException', reason: '-[MedicalDevice setPrice:]: unrecognized selector sent to instance 0x2818cc3c0' - ios

I just inherited this app and I am trying to add a few fields to a form.
I am receiving this error - it seems to be calling a setPrice method on MedicalDevice.
Now as far as I can tell, I've added price to the class that is expecting it...
#objc(MedicalDevice)
public class MedicalDevice: NSManagedObject {
static let entityName = "MedicalDevice"
#nonobjc public class func fetchRequest() -> NSFetchRequest<MedicalDevice> {
return NSFetchRequest<MedicalDevice>(entityName: MedicalDevice.entityName)
}
convenience init(context moc: NSManagedObjectContext) {
self.init(entity: NSEntityDescription.entity(forEntityName: MedicalDevice.entityName, in: moc)!, insertInto: moc)
}
#NSManaged public var createdAt: Date?
#NSManaged public var deviceID: String?
#NSManaged public var expirationDate: Date?
#NSManaged public var lotNumber: String?
#NSManaged public var modelNumber: String?
#NSManaged public var catalogNumber: String?
#NSManaged public var deviceDescription: String?
#NSManaged public var brandName: String?
#NSManaged public var companyName: String?
#NSManaged public var quantity: String?
#NSManaged public var price: String?
#NSManaged public var location: String?
#NSManaged public var facilityID: String?
}
And addDevice works as such - this is where the exception is being thrown:
func addDevice(for deviceID: String, lotNumber: String, expirationDate: Date, modelNumber: String, catalogNumber: String, description: String, quantity: String, brandName: String, companyName: String, price: String, location: String, facilityID: String) {
let medicalDevice = MedicalDevice(context: self.persistentContainer.viewContext)
medicalDevice.createdAt = Date()
medicalDevice.deviceID = deviceID
medicalDevice.lotNumber = lotNumber
medicalDevice.expirationDate = expirationDate
medicalDevice.modelNumber = modelNumber
medicalDevice.catalogNumber = catalogNumber
medicalDevice.deviceDescription = description
medicalDevice.quantity = quantity
medicalDevice.brandName = brandName
medicalDevice.companyName = companyName
medicalDevice.price = price
medicalDevice.location = location
medicalDevice.facilityID = facilityID
self.saveContext()
}
Now, I don't see any setPrice method (which makes sense, I just added it in the various fields), but I also don't see setX, with X being any of the other fields which were definitely saving beforehand.
What could be causing this? Obviously setPrice is somehow being called, somewhere (generated in some way?) and it doesn't exist, I am guessing.

Related

CoreData: How to fetch child objects?

I am trying to fetch child objects (NameCD) of the parent object (CountryCD), but I have a bug:
CountriesAPI[2441:78546] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "parent == %&"'
Is my relationship okay and how do I fix this error?
func fetchCountries() -> [CountryCD] {
do {
let fetchRequest = NSFetchRequest<CountryCD>(entityName: "CountryCD")
fetchRequest.predicate = NSPredicate(format: "parent == %&", "CountryCD")
fetchRequest.returnsObjectsAsFaults = false
let countries = try viewContext.fetch(fetchRequest)
return countries
} catch {
print("CoreDataService - fetchCountries: \(error)")
return []
}
}
import Foundation
import CoreData
extension NameCD {
#nonobjc public class func fetchRequest() -> NSFetchRequest<NameCD> {
return NSFetchRequest<NameCD>(entityName: "NameCD")
}
#NSManaged public var common: String?
#NSManaged public var official: String?
#NSManaged public var countryCD: CountryCD?
}
extension NameCD : Identifiable {
}
import Foundation
import CoreData
extension CountryCD {
#nonobjc public class func fetchRequest() -> NSFetchRequest<CountryCD> {
return NSFetchRequest<CountryCD>(entityName: "CountryCD")
}
#NSManaged public var altSpellings: [String]?
#NSManaged public var area: Double
#NSManaged public var borders: NSObject?
#NSManaged public var callingCodes: [String]?
#NSManaged public var capital: [String]?
#NSManaged public var flag: String?
#NSManaged public var latlng: [Double]?
#NSManaged public var region: String?
#NSManaged public var nameCD: NSSet?
}
// MARK: Generated accessors for nameCD
extension CountryCD {
#objc(addNameCDObject:)
#NSManaged public func addToNameCD(_ value: NameCD)
#objc(removeNameCDObject:)
#NSManaged public func removeFromNameCD(_ value: NameCD)
#objc(addNameCD:)
#NSManaged public func addToNameCD(_ values: NSSet)
#objc(removeNameCD:)
#NSManaged public func removeFromNameCD(_ values: NSSet)
}
extension CountryCD : Identifiable {
}
EDIT:
Ok I made edit and pasted two new screens. I am not sure about the relationship between CountryCD and NameCD. As you can see there is warning on the left side: abstract entity has no children. Maybe this is main problem?

How to save a custom list of objects in Core Data?

I am pretty new in the Core Data and trying to save an array made of custom object but there is small problem: I don't know how to do it the right way. The application retrieves data from the network and writes it to the Core Data database. It contains several arrays and objects that are custom objects. There is no problem with writing strings, ints etc. But how do I save a list of custom objects? The objects used to get data from the web are a bit different to the ones used to work with Core Data, so I can't just assign them. Of course, this can be done in the next loop, but isn't there anything better?
I am completely new to Core Data and I am looking for the best solutions for slightly more complex operations. Is Core Data worth using for complex operations?
CoreDataService:
protocol CoreDataServiceProtocol {
func saveCountries(countries: [Country])
func fetchCountries() -> [CountryCoreData]
}
final class CoreDataService : CoreDataServiceProtocol {
private var persistentContainer: NSPersistentContainer = {
let persistentContainer = NSPersistentContainer(name: "CountriesAPI")
persistentContainer.loadPersistentStores { _, error in
print(error?.localizedDescription ?? "")
}
return persistentContainer
}()
var viewContext: NSManagedObjectContext {
return persistentContainer.viewContext
}
func saveCountries(countries: [Country]) {
for country in countries {
let newCountry = CountryCoreData(context: viewContext)
for currency in country.currencies {
newCountry.addToCurrencyCoreData(currency)
}
//Below, I can easily create a new object that I want to assign as a parent property
var translation = TranslationCoreData(context: viewContext)
translation.br = country.translations?.br
newCountry.addToTranslationCoreData(translation)
//If there is no relationship between the models this way is pretty nice, but in my case there are several relationships
newCountry.setValue(country.alpha2Code, forKey: "alpha2Code")
newCountry.setValue(country.alpha3Code, forKey: "alpha3Code")
newCountry.setValue(country.altSpellings, forKey: "altSpellings")
newCountry.setValue(country.area, forKey: "area")
newCountry.setValue(country.borders, forKey: "borders")
newCountry.setValue(country.callingCodes, forKey: "callingCodes")
newCountry.setValue(country.capital, forKey: "capital")
newCountry.setValue(country.cioc, forKey: "cioc")
// newCountry.setValue(country.currencies, forKey: "currencies")
newCountry.setValue(country.demonym, forKey: "demonym")
newCountry.setValue(country.flag, forKey: "flag")
newCountry.setValue(country.gini, forKey: "gini")
//newCountry.setValue(country.id, forKey: "id")
// newCountry.setValue(country.languages, forKey: "languages")
newCountry.setValue(country.name, forKey: "name")
newCountry.setValue(country.nativeName, forKey: "nativeName")
newCountry.setValue(country.numericCode, forKey: "numericCode")
newCountry.setValue(country.population, forKey: "population")
newCountry.setValue(country.region, forKey: "region")
// newCountry.setValue(country.regionalBlocs, forKey: "regionalBlocs")
newCountry.setValue(country.subregion, forKey: "subregion")
newCountry.setValue(country.timezones, forKey: "timezones")
newCountry.setValue(country.topLevelDomain, forKey: "topLevelDomain")
// newCountry.setValue(country.translations, forKey: "translations")
}
do {
try viewContext.save()
print("Success")
} catch {
print("Error saving: \(error.localizedDescription)")
}
}
Model generated by CoreDataxcdatamodel - CountryCoreData:
import Foundation
import CoreData
extension CountryCoreData {
#nonobjc public class func fetchRequest() -> NSFetchRequest<CountryCoreData> {
return NSFetchRequest<CountryCoreData>(entityName: "CountryCoreData")
}
#NSManaged public var alpha2Code: String?
#NSManaged public var alpha3Code: String?
#NSManaged public var altSpellings: [String]?
#NSManaged public var area: Double
#NSManaged public var borders: [String]?
#NSManaged public var callingCodes: [String]?
#NSManaged public var capital: String?
#NSManaged public var cioc: String?
#NSManaged public var currencies: [CurrencyCoreData]?
#NSManaged public var demonym: String?
#NSManaged public var flag: String?
#NSManaged public var gini: Double
#NSManaged public var id: UUID?
#NSManaged public var languages: [LanguageCoreData]?
#NSManaged public var name: String?
#NSManaged public var nativeName: String?
#NSManaged public var numericCode: String?
#NSManaged public var population: Int16
#NSManaged public var region: String?
#NSManaged public var regionalBlocks: [RegionalBlockCoreData]?
#NSManaged public var subregion: String?
#NSManaged public var timezones: [String]?
#NSManaged public var topLevelDomain: [String]?
#NSManaged public var translations: [TranslationCoreData]?
#NSManaged public var currencyCoreData: NSSet?
#NSManaged public var languageCoreData: NSSet?
#NSManaged public var regionalBlockCoreData: NSSet?
#NSManaged public var translationCoreData: NSSet?
}
// MARK: Generated accessors for currencyCoreData
extension CountryCoreData {
#objc(addCurrencyCoreDataObject:)
#NSManaged public func addToCurrencyCoreData(_ value: CurrencyCoreData)
#objc(removeCurrencyCoreDataObject:)
#NSManaged public func removeFromCurrencyCoreData(_ value: CurrencyCoreData)
#objc(addCurrencyCoreData:)
#NSManaged public func addToCurrencyCoreData(_ values: NSSet)
#objc(removeCurrencyCoreData:)
#NSManaged public func removeFromCurrencyCoreData(_ values: NSSet)
}
// MARK: Generated accessors for languageCoreData
extension CountryCoreData {
#objc(addLanguageCoreDataObject:)
#NSManaged public func addToLanguageCoreData(_ value: LanguageCoreData)
#objc(removeLanguageCoreDataObject:)
#NSManaged public func removeFromLanguageCoreData(_ value: LanguageCoreData)
#objc(addLanguageCoreData:)
#NSManaged public func addToLanguageCoreData(_ values: NSSet)
#objc(removeLanguageCoreData:)
#NSManaged public func removeFromLanguageCoreData(_ values: NSSet)
}
// MARK: Generated accessors for regionalBlockCoreData
extension CountryCoreData {
#objc(addRegionalBlockCoreDataObject:)
#NSManaged public func addToRegionalBlockCoreData(_ value: RegionalBlockCoreData)
#objc(removeRegionalBlockCoreDataObject:)
#NSManaged public func removeFromRegionalBlockCoreData(_ value: RegionalBlockCoreData)
#objc(addRegionalBlockCoreData:)
#NSManaged public func addToRegionalBlockCoreData(_ values: NSSet)
#objc(removeRegionalBlockCoreData:)
#NSManaged public func removeFromRegionalBlockCoreData(_ values: NSSet)
}
// MARK: Generated accessors for translationCoreData
extension CountryCoreData {
#objc(addTranslationCoreDataObject:)
#NSManaged public func addToTranslationCoreData(_ value: TranslationCoreData)
#objc(removeTranslationCoreDataObject:)
#NSManaged public func removeFromTranslationCoreData(_ value: TranslationCoreData)
#objc(addTranslationCoreData:)
#NSManaged public func addToTranslationCoreData(_ values: NSSet)
#objc(removeTranslationCoreData:)
#NSManaged public func removeFromTranslationCoreData(_ values: NSSet)
}
extension CountryCoreData : Identifiable {
}
In my opinion first change these things
Instead of this
newCountry.setValue(country.alpha2Code, forKey: "alpha2Code")
add this line
newCountry.alpha2Code = country.alpha2Code
Do this way on your Save countries function
func saveCountries(countries: [Country]) {
for country in countries {
let newCountry = CountryCoreData(context: viewContext)
newCountry.alpha2Code = country.alpha2Code//add this line
}
saveContext()
}
Create ViewContext function so you can reuse this!
func saveContext(){
do {
try viewContext.save()
print("Success")
} catch {
print("Error saving: \(error.localizedDescription)")
}
}
Using Transformable type you can save array directly in the CoreData without for loop
https://stackoverflow.com/a/29827564/8201581

Assign value related objects core data

I have two entities
#objc(Movies)
public class Movies: NSManagedObject {
}
extension Movies {
#nonobjc public class func fetchRequest() -> NSFetchRequest<Movies> {
return NSFetchRequest<Movies>(entityName: "Movies")
}
#NSManaged public var id: Int64
#NSManaged public var isFav: Bool
#NSManaged public var overview: String?
#NSManaged public var poster: String?
#NSManaged public var release_date: String?
#NSManaged public var title: String?
#NSManaged public var genresID: NSSet?
}
// MARK: Generated accessors for genresID
extension Movies {
#objc(addGenresIDObject:)
#NSManaged public func addToGenresID(_ value: GenresID)
#objc(removeGenresIDObject:)
#NSManaged public func removeFromGenresID(_ value: GenresID)
#objc(addGenresID:)
#NSManaged public func addToGenresID(_ values: NSSet)
#objc(removeGenresID:)
#NSManaged public func removeFromGenresID(_ values: NSSet)
}
#objc(GenresID)
public class GenresID: NSManagedObject {
}
extension GenresID {
#nonobjc public class func fetchRequest() -> NSFetchRequest<GenresID> {
return NSFetchRequest<GenresID>(entityName: "GenresID")
}
#NSManaged public var id: Int64
#NSManaged public var name: String?
#NSManaged public var movieID: Movies?
}
When I click a button an action is triggered to save a movie, and then I would like to save that movie that has been "favored". A movie can have multiples genres (one-to-many relationship).
Method action:
func saveMoviesDB (movie: Movie) {
guard let appDelegate =
UIApplication.shared.delegate as? AppDelegate else {
return
}
let managedContext = appDelegate.persistentContainer.viewContext
let entityMovie = NSEntityDescription.entity(forEntityName: "Movies", in: managedContext)!
let entityGenres = NSEntityDescription.entity(forEntityName: "GenresID", in: managedContext)!
let movieDB = NSManagedObject(entity: entityMovie, insertInto: managedContext)
let genresDB = NSManagedObject(entity: entityGenres, insertInto: managedContext)
movieDB.setValue(movie.id, forKey: "id")
movieDB.setValue(movie.title, forKey: "title")
movieDB.setValue(movie.isFav, forKey: "isFav")
movieDB.setValue(movie.poster, forKey: "poster")
movieDB.setValue(movie.overview, forKey: "overview")
movieDB.setValue(movie.releaseDate, forKey: "release_date")
do{
try managedContext.save()
moviesDB.append(movieDB)
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
}
I don't know how to assign multiple genresID to the Movie. For each movie, there is an Int array containing the Ids of the genres.
EDIT: I decided to remove the genre entity and create a transformable type property in Movies to store the arrays of Int. It went like this:
extension Movies {
#nonobjc public class func fetchRequest() -> NSFetchRequest<Movies> {
return NSFetchRequest<Movies>(entityName: "Movies")
}
#NSManaged public var id: Int64
#NSManaged public var isFav: Bool
#NSManaged public var overview: String?
#NSManaged public var poster: String?
#NSManaged public var release_date: String?
#NSManaged public var title: String?
#NSManaged public var genresID: [NSNumber]?
}
And then I cast it before saving it to the database
let genresID = movie.genre as [NSNumber]

How to access an array of dictionaries in Parse API

I saved an array of dictionaries to Parse, which appears correctly in the User class. I can po user at a breakpoint and the array shows up properly as one of the properties on the User. However, I can't access this data at all, I get a runtime error of EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0). I'm trying to access the data using user.userFbFriendsDetail to save to a local variable. Here is the console result when I po User, I can't figure out how to use the userFBFriendsDetail array. Thanks a lot for your help!
<PFUser: 0x7fe1dd281010, objectId: onHQnYR5d2, localId: (null)> {
facebookID = xxxxxxx
fbEmail = xxxxxx
fbGender = male;
fbName = "John Doe";
friendsUsingTheApp = (
"<PFUser: 0x7fe1dbd30210, objectId: oqKnKZMN3d, localId: (null)>",
"<PFUser: 0x7fe1dbd30510, objectId: hUNZvZC4fD, localId: (null)>"
);
userFbFriendsDetail = (
{
email = "fake#fake.com";
facebookID = 1111111111;
profileImage = "<PFFile: 0x7fe1dfe28422>";
},
{
email = "fake#fake.com";
facebookID = 222222222222;
profileImage = "<PFFile: 0x7fe1dbd1ffd1>";
}
);
}
EDIT: Here is the definition of the PFUser class:
class User : PFUser {
override class func initialize() {
struct Static {
static var onceToken : dispatch_once_t = 0;
}
dispatch_once(&Static.onceToken) {
self.registerSubclass()
}
}
#NSManaged var gender: String?
#NSManaged var fbName: String?
#NSManaged var age: NSNumber?
#NSManaged var facebookID: String?
#NSManaged var fbLocale: String?
#NSManaged var fbTimezone: NSNumber?
#NSManaged var fbGender: String?
#NSManaged var fbEmail: String?
#NSManaged var fbAge: NSNumber?
#NSManaged var profileImage: PFFile?
#NSManaged var twitterHandle: String?
#NSManaged var state: String?
#NSManaged var birthday: String?
#NSManaged var friendsUsingTheApp:Array<String>
#NSManaged var userFbFriendsDetailDict:Dictionary<String, AnyObject>
}
userFbFriendsDetailDict should be of type Array<Dictionary<String, AnyObject>>. (And you should access it under that name, not userFbFriendsDetail).

Parse+Swift, "-[Swift._NSContiguousString objectId]: unrecognized selector sent to instance" error

I'm using Parse and I had a PFObject I was using to represent a "Job". It worked fined, but it was tedious always using setObject:forKey: and objectForKey: rather than accessing properties.
So, I decided to make a "proper" PFObject subclass. Now, every call made to "objectId" gives the above unrecognized selector error -- even calls that have nothing to do with my subclass.
I created my subclass "by the book", as far as I can tell (below), and I do call Job.registerSubclass() before Parse.setApplicationId: in my AppDelegate. Anybody seen this problem?
import Foundation
import Parse
class Job: PFObject, PFSubclassing {
#NSManaged var categoryName: String
#NSManaged var categoryId: String
#NSManaged var state: String
#NSManaged var details: String?
#NSManaged var jobDescription: String
#NSManaged var location: String
#NSManaged var dates: [String]
#NSManaged var images: PFFile?
#NSManaged var questionSequence: [String]?
#NSManaged var consumerResponseIndices: [Int]?
#NSManaged var isPosted: Bool
#NSManaged var bids: [AnyObject]?
override class func initialize() {
struct Static {
static var onceToken : dispatch_once_t = 0;
}
dispatch_once(&Static.onceToken) {
self.registerSubclass()
}
}
class func parseClassName() -> String {
return "Job"
}
}
I got the same issue before.
You may have this error when trying to convert NSArray/NSDictionary to String type, so it turns to NSContiguousString type.
You can check:
dates
questionSequence
consumerResponseIndices
bids
to see if this happened.
In my case the problem was :
if let countryLocale = (notification.userInfo![Constants.CountryLocale]!.firstObject as? String { code }
and solved with
if let countryLocale = (notification.userInfo![Constants.CountryLocale] as! [AnyObject]).first as? String { code }

Resources