我有点迷失并坚持下去并需要帮助。
假设我有两个视图控制器,在View Controller#1中我有一个登录页面,用户通常通过VC#1登录,而在View控制器#2中,我有一个标签,我想显示用户名,在VC#1中输入。
它对我有用,但是它显示了我输入的第一个用户名,而不是最新的用户名。所以我的问题是,如何清除输入到用户名的用户名,因此它不会存储超过1个。
@IBAction func btnLogin(sender: AnyObject)
{
if (txtUsername.text == "")
{
//Show Error Message
let alert = UIAlertView()
alert.title = "Empty Field"
alert.message = "Please enter your username"
alert.addButtonWithTitle("Okay")
alert.show()
}
else if (txtPassword.text == "")
{
//Show Error Message
let alert = UIAlertView()
alert.title = "Empty Field"
alert.message = "Please enter your password"
alert.addButtonWithTitle("Okay")
alert.show()
}
else
{
let appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
let context: NSManagedObjectContext = appDel.managedObjectContext
let request = NSFetchRequest(entityName: "Members")
request.returnsObjectsAsFaults = false
request.predicate = NSPredicate(format: "username = %@", txtUsername.text!)
let results:NSArray = try! context.executeFetchRequest(request)
if results.count > 0
{
let res = results[0] as! NSManagedObject
txtUsername.text = res.valueForKey("username") as? String
txtPassword.text = res.valueForKey("password") as? String
txtUsername.text = ""
txtPassword.text = ""
//Transfers you to another view controller
let secondViewController = self.storyboard!.instantiateViewControllerWithIdentifier("HomePageViewController") as UIViewController
self.presentViewController(secondViewController, animated: true, completion: nil)
}
else
{
//Show Error Message
let alert = UIAlertView()
alert.title = "No such user"
alert.message = "User does not exist"
alert.addButtonWithTitle("Okay")
alert.show()
}
}
}
这是用于在另一个视图控制器中显示用户名的代码(仅1行),其中" lblUsername.text = res.valueForKey(" username")为?串 "
override func viewDidLoad() {
let appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
let context: NSManagedObjectContext = appDel.managedObjectContext
let request = NSFetchRequest(entityName: "Members")
request.returnsObjectsAsFaults = false
let results:NSArray = try! context.executeFetchRequest(request)
index = Int(arc4random_uniform(6))
let res = results[0] as! NSManagedObject
super.viewDidLoad()
circularImage(imageView1)
lblUsername.text = res.valueForKey("username") as? String
//Code to animate images
imageView1.animationImages = [
UIImage(named: Data.images[0])!,
UIImage(named: Data.images[1])!,
UIImage(named: Data.images[2])!,
UIImage(named: Data.images[3])!,
UIImage(named: Data.images[4])!,
UIImage(named: Data.images[5])!
]
imageView1.animationDuration = 15
imageView1.startAnimating()
}