I'm getting this error in Swift 'NSInvalidArgumentException' - arrays

'NSInvalidArgumentException', reason: 'Unacceptable type of value for attribute: property = "save1D"; desired type = NSData; given type = Swift.__SwiftDeferredNSArray;
I've been stuck on this a few days now. I'm trying to save to and load from core data. I'm trying to save arrays from a collection view into a tableview then reload them back into a collection view. I've not been able to find a solution that fits what I need. I'm sure I'm missing something obvious but I can't se it. Can anyone help me with this?
#IBAction func saveData(_ sender: Any) {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "TextSave", in: context)
let textEntity = NSManagedObject(entity: entity!, insertInto: context)
textEntity.setValue(v1, forKey: "save1D")
textEntity.setValue(i1, forKey: "save2D")
textEntity.setValue(ImageView, forKey: "picCock")
do {
try context.save()
print("saved")
} catch {
print("failed save")
}
}
func getData() {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "TextSave")
request.returnsObjectsAsFaults = false
do {
let result = try context.fetch(request)
for data in result as! [NSManagedObject]
{
v1 = data.value(forKey: "save1D") as! [String]
i1 = data.value(forKey: "save2D") as! [String]
ImageView = (data.value(forKey: "picCock") as! UIImageView)
}
} catch {
print("failed")
}
}

Problem is here
textEntity.setValue(v1, forKey: "save1D")
v1 is of type NSData while it should be an array

Related

convert nsmanganedobject to array to find sum of array

My code below is trying to take core data from a NSManagedObject append it to an array. The core data element is saved as a string. My code is not compelling. Ideally the code should be able to append code into the array then the array is filled, find the sum of the numbers added together and print them into the viewDidLoad() func.
var itemName : [NSManagedObject] = []
func performAction() {
let appD = UIApplication.shared.delegate as! AppDelegate
let context = appD.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Data")
request.returnsObjectsAsFaults = false
do {
let result = try context.fetch(request)
var retrievedData = [Double]()
for data in result as! [NSManagedObject] {
if let value = data.value(forKey: "ee") as? Double {
retrievedData.append(value)
}
}
let arraySum = retrievedData.reduce(0, +)
print(arraySum)
} catch {
print("Failed")
}
}
I reviewed your code when you will need to change small thing over there. Replace performAction function as per my updated answer.
func performAction() {
let appD = UIApplication.shared.delegate as! AppDelegate
let context = appD.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Data")
request.returnsObjectsAsFaults = false
do {
let result = try context.fetch(request)
var retrievedData = [Double]()
for data in result as! [NSManagedObject] {
if let value = data.value(forKey: "ee") as? String {
retrievedData.append(Double(value) ?? 0)
}
}
let arraySum = retrievedData.reduce(0, +)
print(arraySum)
} catch {
print("Failed")
}
}

Saving an custom object array that is appended constantly

I'm relatively new to Swift and coding in general. I'm trying to hone my skills at the moment but putting together a simple reminder app. I'm trying to get the back end working before I put together the story board but I have the essential story board elements to test if my system will work.
Basically I'm trying to save a array that contains a custom object, but this array is appended to each reminder addition done by the user. This is so that every time the app opens, the array will contain the reminders from last time.
Here is the code I have so far to create and append the list;
func createReminder() {
let reminderAdd = Reminder(chosenReminderDescription: textRetrieve.text!, chosenReminderLength: 1)
reminderList.append(reminderAdd)
dump(reminderList)
}
Here is the object code;
class Reminder {
var reminderDescription = "Require initalisation."
var reminderLength = 1 // in days
init (chosenReminderDescription: String, chosenReminderLength: Int) {
reminderDescription = chosenReminderDescription
reminderLength = chosenReminderLength
}
}
How would I go about saving the array?
EDIT:
This is what i've added so far.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let reminderAdd = Reminder(chosenReminderDescription: "Placeholder test", chosenReminderLength: 1)
reminderList.append(reminderAdd)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "Tasks", in: context)
let newTask = NSManagedObject(entity: entity!, insertInto: context)
newTask.setValue(reminderList, forKey: "taskName")
do {
try context.save()
} catch {
print("Failed saving")
}
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Tasks")
//request.predicate = NSPredicate(format: "age = %#", "12")
request.returnsObjectsAsFaults = false
do {
let result = try context.fetch(request)
for data in result as! [NSManagedObject] {
print(data.value(forKey: "taskName"))
}
} catch {
print("Failed")
}
I'm getting crashes and I can't seem to debug it as of yet. I believe this line is causing the crash as when I remove it the app launches fine.
let reminderAdd = Reminder(chosenReminderDescription: "Placeholder test", chosenReminderLength: 1)
reminderList.append(reminderAdd)
Any ideas?
EDIT 2:
datamodel
That is the data model, I'm not entirely sure what you mean to make the object into a codable. Thanks again.
EDIT 3:
ViewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let entity = NSEntityDescription.entity(forEntityName: "Tasks", in: context)
let newTask = Tasks(entity: entity!, insertInto: context)
newTask.setValue(reminderList, forKey: "taskName")
do {
try context.save()
} catch {
print("Failed saving")
}
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Tasks")
//request.predicate = NSPredicate(format: "age = %#", "12")
request.returnsObjectsAsFaults = false
do {
let result = try context.fetch(request)
for data in result as! [Tasks] {
print(data.value(forKey: "taskName"))
}
} catch {
print("Failed")
}
dump(reminderList)
}
you could create an instance using CoreData and store it like an internal database.
These are some good tutorial to start with that:
https://medium.com/xcblog/core-data-with-swift-4-for-beginners-1fc067cca707
https://www.raywenderlich.com/7569-getting-started-with-core-data-tutorial
EDIT 2
As you can see in this image,
https://ibb.co/f1axcA
my list in coreData is of type [Notifica], so is an array of object Notifica, to implement codable you should do something like this
public class Notifica: NSObject, NSCoding {
public required init?(coder aDecoder: NSCoder) {
self.id = aDecoder.decodeObject(forKey: "id") as? Double
self.type = aDecoder.decodeObject(forKey: "type") as? String
self.idEvent = aDecoder.decodeObject(forKey: "idEvent") as? Int
self.contactPerson = aDecoder.decodeObject(forKey: "contactPerson") as? People
self.title = aDecoder.decodeObject(forKey: "title") as? String
self.date = aDecoder.decodeObject(forKey: "date") as? String
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(id, forKey: "id")
aCoder.encode(type, forKey: "type")
aCoder.encode(idEvent, forKey: "idEvent")
aCoder.encode(contactPerson, forKey: "contactPerson")
aCoder.encode(title, forKey: "title")
aCoder.encode(date, forKey: "date")
}
ecc..
Another thing is to not call NSManagedObject and pass the entity, but you should name that Tasks as you called in dataModel, if you type Tasks on xcode it will fin for you the NSManagedObject created and then you can set the value for taskName
EDIT 3
"<Simple_Reminders.Reminder: 0x60400046da40>" means that a Reminder object exist! So you saved it! Reminder has two variable:
-reminderDescription and
-reminderLength, so change your code
do {
let result = try context.fetch(request)
for data in result as! [Tasks] {
print(data.value(forKey: "taskName"))
}
} catch {
print("Failed")
}
with this
do {
let result = try context.fetch(request)
for data in result as! [Tasks] {
print(data.value(forKey: "taskName"))
if let reminders = data.value(forKey: "taskName") as? [Reminder] {
for reminder in reminders {
// Now you have your single object Reminder and you can print his variables
print("Your reminder description is \(reminder. reminderDescription), and his length is \(reminder. reminderLength))"
}
}
}
} catch {
print("Failed")
}

Trouble with fetching from core data and putting in array

I'm trying to make a list within core data that can add to an entity "Person" two attributes: age(Int16) and name(string). As far as I can tell i believe it is storing new objects as new ones are added but I dont think my array is fetching them properly. Can someone help me figure where I'm going wrong.
var list = [Person(context:context)]
#IBAction func saveButton(_ sender: Any)
{
list.append(Person(context:context))
list[list.count-1].age = Int16(ageTF.text!)!
list[list.count-1].name = nameTF.text
let newList = NSEntityDescription.insertNewObject (forEntityName: "Person",into: context) as NSManagedObject
newList.setValue(list[list.count-1].name, forKey: "name")
newList.setValue(list[list.count-1].age, forKey: "age")
appDelegate.saveContext()
}
#IBAction func printList(_ sender: Any)
{
for index in 0...list.count-1
{
print("Name of person # \(index) = \(list[index].name!)")
print("Age of person # \(index) = \(list[index].age)")
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Person")
do {
let results = try context.fetch(fetchRequest)
let listItems = results as! [NSManagedObject]
print(listItems)
}
catch {
print("Error")
}
}
The range in your for loop is 0...0 try 0..<list.count
Person(context:context) is functionally the same as NSEntityDescription.insertNewObject (forEntityName: "Person",into: context) as NSManagedObject so you are inserting the object twice into core data.

JSON on Swift: Array to String/TextField Text

I have problem with JSON Array that I want to be display on textfield. JSON is taken from URL. This is JSON structure:
{
description = „This is short decripton”;
);
more-description = (
„this is first line”,
„this is second line”,
„third line”,
„etc”,
„etc”
);
one-more-description = (
„this is first line”,
„this is second line”,
„third line”,
„etc”,
„etc”
);
And this is my code:
import UIKit
class RecipeViewController: UIViewController {
#IBOutlet weak var descriptionTextField: UITextView!
#IBOutlet weak var more-descriptionTextField: UITextView!
#IBOutlet weak var one-more-descriptionTextField: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
let urlAsString = "http://JSON-Address.com"
let url = NSURL(string: urlAsString)!
let urlSession = NSURLSession.sharedSession()
let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in
do {
if let jsonDate = data, let jsonResult = try NSJSONSerialization.JSONObjectWithData(jsonDate, options: []) as? NSDictionary {
print(jsonResult)
let jsonDescription = jsonResult["description"] as? String
print("result: \(jsonDescription)")
let jsonMoreDescrp: AnyObject? = jsonResult["more-description"] as? Array<AnyObject>
print("result: \(jsonMoreDescrp)")
let jsonOneMoreDescrp: AnyObject? = jsonResult["one-more-description"] as? Array<AnyObject>
print("result: \(jsonOneMoreDescrp)")
dispatch_async(dispatch_get_main_queue(),{
self.descriptionTextField.text = jsonDescription
self.more-descriptionTextField.text = jsonMoreDescrp as? String
self.one-more-descriptionTextField.text = jsonOneMoreDescrp as? String
});
}
} catch let error as NSError {
print(error)
}
})
jsonQuery.resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
The problem is with jsonMoreDescrp & jsonOneMoreDescrp. Althought I've changed it to String, after running Xcode the result is empty. jsonDescription of course works, but this is just simple string.
I know I'm doing something wrong with Array, but - can you tell me what?
jsonMoreDescrp & jsonOneMoreDescrp are array. so, you can call like this
self.more-descriptionTextField.text = jsonMoreDescrp[indexValue] as? String
self.one-more-descriptionTextField.text = jsonOneMoreDescrp[indexValue] as? String
Hope this will help you.
Try this way, if it not works comment me the error you come across.
self.more-descriptionTextField.text = jsonMoreDescrp[indexValue].stringValue
self.one-more-descriptionTextField.text = jsonOneMoreDescrp[indexValue].stringValue
indexValue is the key of the value you want in the json.
[Updated] As Sudhir noticed there is also error in code, try this to show comma separated strings:
dispatch_async(dispatch_get_main_queue(),{
self.descriptionTextField.text = jsonDescription
self.more-descriptionTextField.text = (jsonMoreDescrp as? [String])?.joinWithSeparator(",") ?? ""
self.one-more-descriptionTextField.text = (jsonOneMoreDescrp as? [String])?.joinWithSeparator(",") ?? ""
});
Validate JSON structure online before using http://jsonlint.com/
Valid JSON:
{
"description": "This is short decription",
"more-description": [
"this is first line",
"this is second line",
"third line",
"etc",
"etc"
],
"one-more-description": [
"this is first line",
"this is second line",
"third line",
"etc",
"etc"
]
}
try this code, it is much easy to use.
First of all parse all elements of map to the variables and than do what you want with knowing structure of just created variables.
let task = session.dataTask(with: url!) {
(data, response, error) in
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]
if let desc = json["description"] as? String,
let moreDesc = json["more-description"] as? [String],
let oneMoreDesc = json["one-more-description"] as? [String] {
dispatch_async(dispatch_get_main_queue(),{
self.descriptionTextField.text = moreDesc
self.more-descriptionTextField.text = moreDesc.joinWithSeparator("/n")
self.one-more-descriptionTextField.text = oneMoreDesc.joinWithSeparator("/n")
});
}
} catch let error {
print (error)
}
}
task.resume()
I have not tested it, but it should work. Feel free to ask.

Swift: Looping through a Dictionary Array

I'm struggling to loop through an array of dictionary values returned from a web service call.
I've implemented the following code and I seem to be encountering a crash on running.
I'd also like to store the results into a custom Struct. Really having difficulty achieving this and the answers on here so far haven't worked. Would be grateful if someone is able to help.
let nudgesURLString = "http://www.whatthefoot.co.uk/NUDGE/nudges.php"
let nudgesURL = NSURL(string: nudgesURLString)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(nudgesURL!, completionHandler: {data, response, error -> Void in
if error != nil {
println(error)
} else {
let nudgesJSONResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
let nudges: NSDictionary = nudgesJSONResult["nudges"] as NSDictionary
if let list = nudgesJSONResult["nudges"] as? [[String:String]] {
for nudgeDict in list {
let location = nudgeDict["location"]
println(location)
}
}
}
})
task.resume()
}
NOTICE
This answer was written using Swift 1.2 and as such, there may be some slight stylistic and syntax changes required for the answer to work depending on your current Swift system.
Answer -- Swift 1.2
This line is crashing your code:
let nudges: NSDictionary = nudgesJSONResult["nudges"] as NSDictionary
You're forcing a cast that Swift can't handle. You never make it to your for-loop.
Try changing your code to look more like this:
let nudgesURLString = "http://www.whatthefoot.co.uk/NUDGE/nudges.php"
let nudgesURL = NSURL(string: nudgesURLString)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(nudgesURL!, completionHandler: {data, response, error -> Void in
if error != nil {
println(error)
} else {
let nudgesJSONResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as [String : AnyObject]
if let nudges = nudgesJSONResult["nudges"] as? [[String : String]] {
for nudge in nudges {
let location = nudge["location"]
println("Got location: \(location)")
println("Got full nudge: \(nudge)")
}
}
}
})
task.resume()
Thanks,
I created the following Struct which stored the data, and also lets me create dictionaries in the view controller for a particular index.
struct NudgesLibrary {
var location: NSArray?
var message: NSArray?
var priority: NSArray?
var date: NSArray?
var nudges: NSArray?
init(nudgesObject: AnyObject) {
nudges = (nudgesObject["nudges"] as NSArray)
if let nudges = nudgesObject["nudges"] as? NSArray {
location = (nudges.valueForKey("location") as NSArray)
message = (nudges.valueForKey("message") as NSArray)
priority = (nudges.valueForKey("priority") as NSArray)
date = (nudges.valueForKey("date") as NSArray)
}
}
}

Resources