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).
Related
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.
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 }
I have a User model class (generated by XCode with Swift):
#objc(User)
class User: NSManagedObject { }
And it's extension:
extension User {
#NSManaged var id: NSNumber?
#NSManaged var firstName: String?
#NSManaged var lastName: String?
#NSManaged var birthYear: NSNumber?
}
I can save/fetch data from CoreData.
But can I use this class for object management without CoreData things? Or i need to create other class/struct for this?
For example, create User object (without ObjectContext), set his attributes and send it as property in some func? Maybe i can create some struct in class User (like struct {var firstNameData, secondNameData,...}) and use it in code?
I updated class:
struct User {
var id: Int!
var firstName: String!
var lastName: String!
var birthYear: UInt?
}
#objc(UserManagedObject)
class UserManagedObject: NSManagedObject {
func toStruct() -> User {
var userData = User()
userData.id = Int(self.id)
userData.firstName = self.firstName
userData.lastName = self.lastName
if let by = self.birthYear {
userData.birthYear = UInt(by)
}
return userData
}
}
Now for object management i use struct User and UserManagedObject for CoreData in/out
I am trying to use Core Data to save some of my application data. I have following classes. Basically I want to store the properties of each job, and use it later on.
Following is the class I currently use in my application.
class Job {
var name:String?
var count = 1
var id:String
var startDate:NSDate?
var finishDate:NSDate?
var expected:NSDate?
var detail:Array<JobDetail> = []
var isFinished:Bool?
var sender:String?
var receiver:String?
init(name:String?, id:String) {
self.name = name
self.id = id
self.isFinished = false
self.startDate = NSDate()
}
func addDetail (message:String?, date:NSDate?, location:String?, status: DetailStatus) {
detail.append(JobDetail(message: message, date: date, location: location, status: status))
if status == DetailStatus.OK {
self.isFinished = true
self.finishDate = date
}
}
}
enum DetailStatus {
case OK
case Error
case Exception
case Unknown
}
class JobDetail {
var message:String?
var date:NSDate?
var location:String?
var status:DetailStatus
init(message:String?, date:NSDate?, location:String?, status: DetailStatus) {
self.message = message
self.date = date
self.location = location
self.status = status
}
}
NSManagedObject sub class I created with Xcode after I create the data model.
class Job: NSManagedObject {
#NSManaged var name: String
#NSManaged var count: NSNumber
#NSManaged var id: String
#NSManaged var startDate: NSDate
#NSManaged var finishDate: NSDate
#NSManaged var expected: NSDate
#NSManaged var isFinished: NSNumber
#NSManaged var sender: String
#NSManaged var receiver: String
#NSManaged var details: NSSet
}
class JobDetail: NSManagedObject {
#NSManaged var message: String
#NSManaged var date: NSDate
#NSManaged var location: String
#NSManaged var status: NSNumber
#NSManaged var parent: Job
}
Here are the screenshots of my data model.
Basically I want to CRUD Job in my application so that I can show them in my tableview. I have everything setup, but because I couldn’t setup Core Data I don’t have persistence. I will appreciate if you can help me to setup Core Data.
Refer this. May be it's useful to you...
http://www.raywenderlich.com/85578/first-core-data-app-using-swift
It seems from the screenshots that your setup is correct. Link details with jobs like this.
detail1.parent = job
detail2.parent = job
context.save(nil)
Get all details for a job like this
job.details
This is unordered, but you can sort them using sortedArrayUsingDescriptors.
let sortedDetails = job.details.sortedArrayUsingDescriptors(
[NSSortDescriptor(key:"date" ascending: false)])
I am trying to write some info to Core Data using the new NSBatchUpdateRequest and can't figure out why I am getting this error. Can someone explain what is going on here? It sounds like I am having trouble converting a Swift to Objective-C type value?
fatal error: value failed to bridge from Swift type to Objective-C type
Here is my block of code that the error is taking place in:
func updateUser(user: User) {
var batchRequest = NSBatchUpdateRequest(entityName: "User")
if doesUserExist(user.userId) {
batchRequest.predicate = NSPredicate(format: "userId == %#", user.userId)
}
batchRequest.propertiesToUpdate = [
"userId" : user.userId,
"username" : user.username,
"email" : user.email,
"fullName" : user.fullName,
"gender" : user.gender,
"birthdate" : user.birthdate,
"zipCode" : user.zipCode,
"aboutMe" : user.aboutMe,
"iAm" : user.iAm,
"iLike" : user.iLike,
"favoriteWeapon" : user.favoriteWeapon,
"dateCreated" : user.dateCreated,
"lookingFor" : user.lookingFor,
"minAge" : user.minAge,
"maxAge" : user.maxAge,
"distance" : user.distance,
"gameOwned" : user.gameOwned,
"gameSetting" : user.gameSetting,
"allowedList" : user.allowedList,
"blockedList" : user.blockedList,
"avatarType" : user.avatarType
]
batchRequest.resultType = .UpdatedObjectsCountResultType
var error : NSError?
var results = self.managedObjectContext!.executeRequest(batchRequest, error: &error) as NSBatchUpdateResult
if error == nil {
println("Updated User: \(user.username) \(results.result)")
}
else {
println("Update User Error: \(error?.localizedDescription)")
}
}
The line of code that I am getting the error on is:
var results = self.managedObjectContext!.executeRequest(batchRequest, error: &error) as NSBatchUpdateResult
User Object
class User: NSManagedObject {
#NSManaged var aboutMe: String
#NSManaged var avatarType: String
#NSManaged var birthdate: NSDate
#NSManaged var cityState: String
#NSManaged var dateCreated: NSDate
#NSManaged var distance: NSNumber
#NSManaged var email: String
#NSManaged var favoriteWeapon: String
#NSManaged var fullName: String
#NSManaged var gameOwned: AnyObject
#NSManaged var gameSetting: AnyObject
#NSManaged var gender: String
#NSManaged var iAm: String
#NSManaged var iLike: String
#NSManaged var lastMatch: NSDate
#NSManaged var lookingFor: String
#NSManaged var maxAge: NSNumber
#NSManaged var minAge: NSNumber
#NSManaged var pictureUrl: String
#NSManaged var userId: String
#NSManaged var username: String
#NSManaged var zipCode: String
#NSManaged var allowedList: String
#NSManaged var blockedList: String
}
Most likely your user object has swift specific features that are not available in objective c, like enums, tuples, generics, etc.
This could be an issue in the complier being cause by your swift optimization. One solution that worked for me was
Click on your target in the left sidebar.
Click on Build Settings
Search for 'Optimization level'
Change the values as required (we had to set the Optimization Level to -Onone to fix the bug)
Source:How to Change the Optimization Level in Xcode 6 for Swift
You should convert all your variables containing data to String data type. Maybe your 'AnyObject' or 'Date' datatypes are creating the problem.