I have one to many relationship in my coredata model. For each News object I have many details object.
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: NSOrderedSet
}
class JobDetail: NSManagedObject {
#NSManaged var message: String
#NSManaged var date: NSDate
#NSManaged var location: String
#NSManaged var status: NSNumber
#NSManaged var parent: Job
}
So, how can I remove all details from Job? My current approach is to delete Job itself and create it again which is slower.
I have tried to delete with,
context?.deletedObjects(myJob.detail)
but it didn’t work. It says
'(#lvalue NSOrderedSet) -> _' is not identical to 'Set'
It seems that you mixed-up deleteObject() with deletedObjects().
deletedObjects() is a method to get a list of all managed objects which
have been marked for deletion in the managed object context. What you have to call is deleteObject()
for each object. Something like (not compiler-checked):
for detail in myJob.details {
context.deleteObject(detail)
}
Related
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 }
In my calendarViewController I'd like to prepare an array containing dates. In my model i have to-may relationship where one medicine can have multiple dates of taking pill. How can i perform a loop through this set to append an array ?
My models:
extension Medicine {
#NSManaged var amount: String?
#NSManaged var endDate: String?
#NSManaged var name: String?
#NSManaged var time: String?
#NSManaged var notificationSet: NSNumber?
#NSManaged var taken: NSOrderedSet?
}
Model Dates
extension Dates {
#NSManaged var date: NSDate?
#NSManaged var takes: Medicine?
}
I'd like to perform loop like this ,but instead these dates i'd like those from CoreData:
var dates = [NSDate(timeIntervalSinceNow: 60*60*24*2), NSDate(timeIntervalSinceNow: 60*60*24*3), NSDate(timeIntervalSinceNow: 60*60*24*5), NSDate(timeIntervalSinceNow: 60*60*24*7)]
func calendar(calendar: CKCalendarView!, configureDateItem dateItem: CKDateItem!, forDate date: NSDate!) {
for dateTaken in dates {
if calendar.date(date, isSameDayAsDate: dateTaken) {
dateItem.backgroundColor = UIColor.redColor()
}
}
}
Fetch your Medicine entity and then create the array like this:
let dates = medicine.taken.map { $0.date }
Not sure about the NSOrderedSet which tends to be buggy so I generally avoid it, but you can try appending as! [NSDate] to make sure you have an proper array of dates.
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.
Does anyone know, or have an example of, how to handle core data transient values with Swift? I know to use #NSManaged before the properties, but can't figure out how to code the logic to build the transient values using Swift.
Check mark the transient field in your data model for particular attribute(e.g. sectionTitle).
Create class for that entity, it will look something like
class Message: NSManagedObject {
#NSManaged var body: String?
#NSManaged var time: NSDate?
#NSManaged var sectionTitle: String?
}
Edit it and make it like this:
class Message: NSManagedObject {
#NSManaged var body: String?
#NSManaged var time: NSDate?
var sectionTitle: String? {
return time!.getTimeStrWithDayPrecision()
//'getTimeStrWithDayPrecision' will convert timestamp to day
//just for e.g.
//you can do anything here as computational properties
}
}
Update- Swift4
Use #objc tag for Swift 4 as:
#objc var sectionTitle: String? {
return time!.getTimeStrWithDayPrecision()
}
We should use willAccessValueForKey and didAccessValueForKey to support KVO