This question has arisen numerous times, but I still haven't found a satisfactory resolution for Xcode 7 Beta.
An error appears on the following line:-
contxt.save(nil) {
The error states...... "Extra argument in call"
what does this mean and can someone please show me the Swift coding required to solve this error?
I have copied most of my code below.
Thanx Del
#IBOutlet weak var locationTextField: UITextField! = nil
#IBOutlet weak var areaTextField: UITextField! = nil
#IBOutlet weak var postCodeTextField: UITextField! = nil
#IBOutlet weak var longLatTextField: UITextField! = nil
#IBOutlet weak var remarksTextField: UITextField! = nil
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func saveButtonPressed(sender: UIBarButtonItem) {
//Reference To Our App Delegate
let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
// Reference moc
let contxt: NSManagedObjectContext = appDel.managedObjectContext
let en = NSEntityDescription.entityForName("list", inManagedObjectContext: contxt)
// Create Instance Of Our Data Model And Initialise
let newItem = Model(entity: en!, insertIntoManagedObjectContext: contxt)
// Map Our Properties
newItem.location = locationTextField.text!
newItem.area = areaTextField.text!
newItem.postCode = postCodeTextField.text!
newItem.longLat = longLatTextField.text!
newItem.remarks = remarksTextField.text!
// Save Our Context
// contxt.save(&ErrorType.self)
// print(newItem)
contxt.save(nil) {
print(newItem)
// Navigate Back To Root vc
self.navigationController!.popToRootViewControllerAnimated(true)
}
func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
Related
I'm trying to make a leaderboard for a word scrambler app so I am saving the data before segueing to the next view controller which will eventually be a leaderboard. My outlets are all connected and the segue identifier was written correctly so I don't see why the app crashes after done is pressed
the error line occurs here: class AppDelegate: UIResponder, UIApplicationDelegate {
var finalScore = Int()
var playerName = String()
var allMyStoredData = UserDefaults.standard
class secondVC: UIViewController {
#IBOutlet weak var scoreLabel: UILabel!
#IBOutlet weak var nameTF: UITextField!
#IBOutlet weak var doneButton: UIButton!
var playerScore = 0
override func viewDidLoad() {
super.viewDidLoad()
scoreLabel.text = "Your score is: \(finalScore)"
loadData()
}
#IBAction func donePressed(_ sender: Any) {
saveData()
//this part won't execute
performSegue(withIdentifier: "toLeaderboard", sender: self)
}
func saveData () {
playerName = nameTF.text!
playerScore = finalScore
allMyStoredData.set(playerName, forKey: "saveTheName")
allMyStoredData.set(playerScore, forKey: "saveTheScore")
}
func loadData () {
if let loadPlayerName:String = UserDefaults.standard.value(forKey: "saveTheName") as? String {
playerName = loadPlayerName
}
if let loadTheScore:Int = UserDefaults.standard.value(forKey: "saveTheName") as? Int {
playerScore = loadTheScore
}
}
}
Update: there was an outlet in the view controller the segue "toLeaderboard" goes to which wasn't connected or used so I deleted it and now the code is fine
I'm following a very simple swift course and while everything works for the instructor the same code does not execute on my side and I'm trying to understand why is that happening.
The app is very simple, is consists of adding tasks to a TableView with a name and a switch to determine if those are important (in which case an emoji is added to the name)
While trying to access and modify the "name" attribute of my "Taskentity" core data entity, the editor gives me the error "Value of type "Taskentity" has no member "name"".
The code is the following :
import UIKit
class AddTaskViewController: UIViewController {
#IBOutlet weak var textField: UITextField!
#IBOutlet weak var isImp: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func btnTapped(_ sender: Any) {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let task = Taskentity(context: context)
task.name = textField.text! // **!error!**
task.isImportant = isImp.isOn
(UIApplication.shared.delegate as! AppDelegate).saveContext()
navigationController!.popViewController(animated: true)
}
}
And my Core Data file looks like this :
Thanks for any help!
Your screen shot shows the problem perfectly. You have named the attribute corename, not name. So naturally the name name is not its name!
You have a problem with you attributes. The one titled 'corename' which is a string should be renamed to 'name' Xcode cannot tell what .name means because you have nothing that Devi gets what it is.
I have attached how your code should look to fix this problem:
import UIKit
class AddTaskViewController: UIViewController {
#IBOutlet weak var textField: UITextField!
#IBOutlet weak var isImp: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func btnTapped(_ sender: Any) {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let task = Taskentity(context: context)
task.corename = textField.text! // **!error!**
task.isImportant = isImp.isOn
(UIApplication.shared.delegate as! AppDelegate).saveContext()
navigationController!.popViewController(animated: true)
}
}
Usual AVAudioPlayer tutorials online creates a AVAudioPlayer within a function to where the play and stop functions of the AVAudioPlayer object aren't available to the object directly from other functions. The problem is that I would like another function to stop the sound from the AVAudioPlayer. This seems pretty simple by initializing the objects at the top of the class in hopes it would be accessible however in Swift3 the init function for AVAudioPlayer includes a throw and a parameter for the sound file. Swift doesn't allow us to use an instance member within a property initializer so I'm stuck on my thought process of how this could be written.
The only error I'm running into at this point is not being allowed to use an instance member in the property initializer when creating "backgroundMusicPlayer":
import UIKit
import AVFoundation
class MadLibOneViewController: UIViewController, UITextFieldDelegate {
#IBOutlet weak var thePlace: UITextField!
#IBOutlet weak var theVerb: UITextField!
#IBOutlet weak var theNumber: UITextField!
#IBOutlet weak var theTemplate: UITextView!
#IBOutlet weak var theStory: UITextView!
#IBOutlet weak var generateStoryButton: UIButton!
#IBOutlet weak var proceedToNextMadLib: UIButton!
//var backgroundMusicPlayer = AVAudioPlayer()
var error:NSError?
var path = Bundle.main.path(forResource: "bensound-cute", ofType: "mp3")
var url: NSURL {
return NSURL(fileURLWithPath: path!)
}
var backgroundMusicPlayer: AVAudioPlayer = try AVAudioPlayer(contentsOf: url as URL, error: &error)
#IBAction func createStory(_ sender: AnyObject) {
theStory.text=theTemplate.text
theStory.text=theStory.text.replacingOccurrences(of: "<place>", with: thePlace.text!)
theStory.text=theStory.text.replacingOccurrences(of: "<verb>", with: theVerb.text!)
theStory.text=theStory.text.replacingOccurrences(of: "<number>", with: theNumber.text!)
generateStoryButton.isHidden=true
proceedToNextMadLib.isHidden=false
}
#IBAction func showNextStory(_ sender: AnyObject) {
view.backgroundColor=UIColor.green
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let resultViewController = storyBoard.instantiateViewController(withIdentifier: "MadLibTwoViewController") as! MadLibTwoViewController
self.present(resultViewController, animated:true, completion:nil)
}
#IBAction func hideKeyboard(_ sender: AnyObject) {
thePlace.resignFirstResponder()
theVerb.resignFirstResponder()
theNumber.resignFirstResponder()
theTemplate.resignFirstResponder()
}
override func viewDidLoad() {
super.viewDidLoad()
proceedToNextMadLib.isHidden=true
view.backgroundColor = UIColor.purple
// Do any additional setup after loading the view.
self.theVerb.delegate = self
self.thePlace.delegate = self
self.theNumber.delegate = self
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
You need to use Lazy initialisation/instantiation for that. In your case this is all you need to do.
lazy var player: AVAudioPlayer = {
[unowned self] in
do {
return try AVAudioPlayer.init(contentsOf: self.url)
}
catch {
return AVAudioPlayer.init()
}
}()
For more about Lazy Initialisation this is a good read. The interesting thing in your case is that the initialiser throws. I think this forum discussion is helpful to have a slight idea.
In my app I am using segue to pass data between two viewcontrollers and that should be easy enough, but for som reason I can`t see there I keep getting "Unresolved Identifier"
Her are some of the code that has to do with that function.
from ViewController 1
import UIKit
import CoreData
class ViewController: UIViewController, UITextFieldDelegate
{
#IBOutlet var panelWidthTextField: UITextField!
#IBOutlet var panelHightTextField: UITextField!
#IBOutlet var panelsWideTextField: UITextField!
#IBOutlet var panelsHightTextField: UITextField!
#IBOutlet var panelPitchTextField: UITextField!
#IBOutlet var calculateButton: UIButton!
#IBOutlet var resultWithLabel: UILabel!
#IBOutlet var resultHightLabel: UILabel!
#IBOutlet var fillAllFieldsLabel: UILabel!
var pawidth:String!
var pahight:String!
var papitch:String!
override func viewDidLoad()
{
super.viewDidLoad()
panelWidthTextField.text = pawidth
panelHightTextField.text = pahight
panelPitchTextField.text = pap itch
From Second ViewController
import UIKit
import CoreData
class DataBase: UIViewController, UITextFieldDelegate
{
#IBOutlet var makerTextField: UITextField!
#IBOutlet var modelTextField: UITextField!
#IBOutlet var stPanelWidthTextField: UITextField!
#IBOutlet var stPanelHightTextField: UITextField!
#IBOutlet var stPitchTextField: UITextField!
let moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
// Removes keyboard when touch outside edit field.
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?)
{
view.endEditing(true)
super.touchesBegan(touches, withEvent: event)
}
#IBAction func saveButton(sender: UIButton)
{
let ed = NSEntityDescription.entityForName("Ledinfo", inManagedObjectContext: moc)
let model = Ledinfo(entity:ed!, insertIntoManagedObjectContext:moc)
model.manufactor = makerTextField.text
model.model = modelTextField.text
model.panelwidth = stPanelWidthTextField.text
model.panelhight = stPanelHightTextField.text
model.pitch = stPitchTextField.text
do {
try moc.save()
makerTextField.text = ""
modelTextField.text = ""
stPanelWidthTextField.text = ""
stPanelHightTextField.text = ""
stPitchTextField.text = ""
Alert.show("Succsess", message: "Your Record Is Saved", vc: self)
}
catch _ as NSError
{
Alert.show("Failed", message: "Something Went Wrong", vc: self)
}
}
#IBAction func searchButton(sender: UIButton)
{
let ed = NSEntityDescription.entityForName("Ledinfo", inManagedObjectContext: moc)
let req = NSFetchRequest()
req.entity = ed
let cond = NSPredicate(format: "manufactor = %#", makerTextField.text!)
req.predicate = cond
do {
let result = try moc.executeFetchRequest(req)
if result.count > 0
{
let model = result[0] as! Ledinfo
makerTextField.text = model.manufactor
modelTextField.text = model.model
stPanelWidthTextField.text = model.panelwidth
stPanelHightTextField.text = model.panelhight
stPitchTextField.text = model.pitch
} else
{
Alert.show("Failed", message: "No Record Is Found", vc: self)
}
} catch _ as NSError!
{
Alert.show("Failed", message: "No Record Is Found" , vc: self)
}
}
#IBAction func transfereButton(sender: UIButton) {
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if (segue.identifier == "transfereButton") {
let svc = segue.destinationViewController as! ViewController
svc.pawidth = stPanelWidthTextField.text
svc.pahight = stPanelHightTextField.text
svc.papitch = stPitchTextField.text
}
}
}
It can not find panelWidthTextField.text, panelHightTextField.text and panelPitchTextField.text as identifier.
I have check spelling and just can`t seem to be able to find what is missing.
Any help is appreciated
"Segue" means, that in "prepareForSegue" method you set the property of ViewController to some data in your DataBase controller. In your example, this can be done like this:
svc.pawidth = someDataFromDataBaseWhichYouWantToPassToSecondVC
svc.pahight = someDataFromDataBaseWhichYouWantToPassToSecondVC
svc.papitch = someDataFromDataBaseWhichYouWantToPassToSecondVC
And then, you can manipulate this data from your ViewController class.
You mistake that you are not passing the data from one VC to another, instead of that you are trying to set the property of 1stVC to another property of 1stVC, and there is no segue needed.
This has nothing to do with segues. do you have 3 text fields in your DataBase class with names panelWidthTextField, panelHightTextField and panelPithcTextField? It's complaining about not being able to find those variables.
You should call the performSegueWithIdentifier("transfereButton", sender: nil) inside your transfereButton IBOutlet action to actually make the prepareForSegue to run.
I am trying to save an inputted string from a text field and load that saved value using NSUserDefaults. When I run my code, the app crashes when I hit the "saveScore" button. My error message is "terminating with uncaught exception," but I can't find what's actually wrong.
class ScoreViewController: UIViewController {
#IBOutlet weak var loadDataButton: UIButton!
#IBOutlet weak var mathScore: UITextField!
#IBOutlet weak var testMath: UILabel!
#IBOutlet weak var saveScore: UIButton!
#IBOutlet weak var displayDataLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func saveDataClicked(sender: AnyObject) {
saveData()
}
func saveData() {
let defaults = NSUserDefaults.standardUserDefaults()
let latestScore = mathScore.text
defaults.setObject(latestScore, forKey: "12/1")
defaults.synchronize()
}
#IBAction func loadDataClicked(sender: AnyObject) {
var defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
if let firstNameIsNotNill = defaults.objectForKey("12/1") as? String {
self.displayDataLabel.text = defaults.objectForKey("12/1") as String
}
}
Restarting XCode fixed the problem!