当我从另一个视图控制器调用时,为什么我的表视图为零?

时间:2015-04-06 11:15:20

标签: ios uitableview swift uilabel iboutlet

当用户通过将表视图中的标签设置为“ONLY MEMBER”时,我试图从左侧菜单(滑出)重新加载我的表视图控制器。所以,我调用了refreshAuctionLatestViewController.viewWillAppear(true)。但是,将在该方法中重新加载的表视图为nil.Any Helps?

这是我的幻灯片菜单控制器(SlideMenu)

import UIKit


class LeftMenuViewController: UIViewController ,UITableViewDataSource, UITableViewDelegate{

@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var userEmail: UIButton!
@IBOutlet weak var btnLogOut: UIButton!
var refreshActionLatestController:AuctionLatestViewController!

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(true)

    let isLoggedIn = TegKeychain.get("isLoginIn")
    let userEmail = TegKeychain.get("userEmail_keyChain")
    if (isLoggedIn != "1") {
        self.btnLogOut.enabled = false
        self.btnLogOut.hidden = true
        self.userEmail.enabled = true
    }else if userEmail != nil{
        self.userEmail.titleLabel?.text = userEmail
        self.userEmail.enabled = false
        self.btnLogOut.enabled = true
        self.btnLogOut.hidden = false
    }
}
@IBAction func logoutTapped(sender : UIButton) {

    refreshActionLatestController = AuctionLatestViewController()

    self.slideMenuController()?.closeLeft() //Closing the Slide and show user with alert on main view controller

    let logOutAlertController = UIAlertController(title : "Log Out",message: "Are You Sure You Gonna Log Out?",preferredStyle : .ActionSheet)

    let callAction = UIAlertAction(title: "Log Out", style: .Default, handler: {
        action in

        var token:NSString = TegKeychain.get("userToken_keyChain")!
        var email:NSString = TegKeychain.get("userEmail_keyChain")!

        var params : Dictionary <String,String> = ["appid" : token, "email" : email]
        var params2 = self.createStringFromDictionary(params)
        var paramsLength = "\(countElements(params2))"

        var err: NSError?

        NSLog("PostData: %@",params2);

        var url:NSURL = NSURL(string:"http://localhost:8080/xx/xxx/account/logout")!

        var requestBodyData = (params2 as NSString).dataUsingEncoding(NSUTF8StringEncoding)


        var request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
        request.HTTPMethod = "POST"
        request.HTTPBody = requestBodyData
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.setValue("application/json", forHTTPHeaderField: "Accept")


        var reponseError: NSError?
        var response: NSURLResponse?

        var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)

            if ( urlData != nil ) {
                let res = response as NSHTTPURLResponse!;

                NSLog("Response code: %ld", res.statusCode);

                if (res.statusCode >= 200 && res.statusCode < 300)
                {
                    var responseData:NSString  = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!

                    NSLog("Response ==> %@", responseData);

                    var err: NSError?

                    let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &err) as NSDictionary

                    let status:NSString = jsonData.valueForKey("status") as NSString

                    //let error:NSString = jsonData.valueForKey("error") as NSString

                    NSLog("Status:", status);
                    NSLog("Error:", status);

                    if(status == "ok")
                    {
                        NSLog("Log Out SUCCESS");

                        TegKeychain.delete("userEmail_keyChain")
                        TegKeychain.delete("isLoginIn")
                        TegKeychain.delete("userToken_keyChain")
                        TegKeychain.delete("userName_keyChain")



    self.refreshActionLatestController?.viewWillAppear(true) //doesn't work,keep showing me nil at carTableView
    //self.refreshActionLatestController?.searchForResults(true) 
    // I already initialize that main view controlller,but table view of that main view still showing nil when i created output of it.

                        self.userEmail.titleLabel?.text = "Sign In"
                        self.userEmail.enabled = true
                        self.btnLogOut.enabled = false
                        self.btnLogOut.hidden = true
                    }
                    else if status == "error"{

                        var alertView:UIAlertView = UIAlertView()
                        alertView.title = "Log Out Failed!"
                        alertView.message = "Connection Failed"
                        alertView.delegate = self
                        alertView.addButtonWithTitle("OK")
                        alertView.show()
                    }
                } else {
                    TegKeychain.delete("userEmail_keyChain")
                    TegKeychain.delete("isLoginIn")
                    TegKeychain.delete("userToken_keyChain")
                    TegKeychain.delete("userName_keyChain")

                    self.userEmail.titleLabel?.text = "Sign In"
                    self.btnLogOut.enabled = false
                    self.btnLogOut.hidden = true
                    self.dismissViewControllerAnimated(true, completion: nil)

                    var alertView:UIAlertView = UIAlertView()
                    alertView.title = "Already Log Out!"
                    alertView.message = "You account has been already log out"
                    alertView.delegate = self
                    alertView.addButtonWithTitle("OK")
                    alertView.show()
                }
            }
            else {
                var alertView:UIAlertView = UIAlertView()
                alertView.title = "Log Out Failed!"
                alertView.message = "Connection Failed"
                alertView.delegate = self
                alertView.addButtonWithTitle("OK")
                alertView.show()
            }
        }
    )
    logOutAlertController.addAction(callAction)

    let defaultAction = UIAlertAction(title: "Cancel", style: .Default, handler: nil)
    logOutAlertController.addAction(defaultAction)
    presentViewController(logOutAlertController, animated: true, completion: nil)
}

func createStringFromDictionary(dict: Dictionary<String,String>) -> String {
    var params = String()
    for (key, value) in dict {
        params += "&" + key + "=" + value
    }
    return params
}
}

这是我的主视图控制器[这是拍卖车列表]

import UIKit

class AuctionLatestViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,AuctionAPIProtocol{

@IBOutlet var carTableView : UITableView?
@IBOutlet var carTableIndicator : UIActivityIndicatorView?
@IBOutlet var retryButton:UIButton?

var latestCars = [AuctionModel]()
var api : AuctionAPI?
var imageCache = [String : UIImage]()
var token : String = " "
var lotId : String = " "
var page : String = " "

override func viewDidLoad() {
    println("Auction Latest : viewDidLoad")
    super.viewDidLoad()
    self.setNavigationBarItem()
    self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .Plain, target: nil, action: nil)

    carTableView?.hidden = true
    retryButton?.hidden=true
    carTableIndicator?.center
    carTableIndicator?.startAnimating()

    if TegKeychain.get("userToken_keyChain") == nil{
        token = "null"
    }
    else{
        token = TegKeychain.get("userToken_keyChain")!
    }
    lotId = "1"
    page = "1"

    api = AuctionAPI(delegate: self)
    api!.searchAuctionLatestFor(token,lotId: lotId,page: page)
}

override func viewWillAppear(animated: Bool) {
    println("Auction Latest : ViewWillAppear")

    super.viewWillAppear(animated)
    self.setNavigationBarItem()
    if TegKeychain.get("userToken_keyChain") == nil{
        token = "null"
    }
    else{
        token = TegKeychain.get("userToken_keyChain")!
    }
    lotId = "1"
    page = "1"
    api = AuctionAPI(delegate: self)
    api!.searchAuctionLatestFor(token,lotId: lotId,page: page)
}

//Table View DataSource and Delegate

// Implementing the json results from api.
func didReceiveAPIResults(results: NSDictionary) {
    var resultsArr: NSArray = results["body"] as NSArray //fix
    dispatch_async(dispatch_get_main_queue(), {
        self.latestCars = AuctionModel.latestWithJSON(resultsArr)
        println(self.carTableView)

        self.carTableView?.reloadData() // I reload the table view
        println(self.carTableView)// which return nil when i called from Slide Menu Controller.But return data,if the main view controller called.

        self.retryButton?.hidden=true
        self.retryButton?.enabled=false
        self.carTableIndicator?.stopAnimating()
        self.carTableView?.hidden = false
    })
}

// The function that i call from slide menu when log out
func searchForResults(search:Bool){
    println("Search Again")

    retryButton?.enabled=false
    retryButton?.hidden=true
    carTableIndicator?.startAnimating()
    api = AuctionAPI(delegate: self)

    if TegKeychain.get("userToken_keyChain") == nil{
        token = "null"
    }
    else{
        token = TegKeychain.get("userToken_keyChain")!
    }
    lotId = "1"
    page = "1"

    api = AuctionAPI(delegate: self)
    api!.searchAuctionLatestFor(token,lotId: lotId,page: page)
    //it will go to didReceiveAPIResults() method
}

这是我的控制台输出,你会在下面看到nil。

PostData: &appid=9cdcf896d1f54c3c11b0d4839ce26775
Response ==> {"status":"authorized"}
Status:
Already Sign In
Auction Latest : viewDidLoad
Auction Latest : ViewWillAppear
task completed
Optional(<UITableView: 0x7faa9c852000; framet a=s k( 0c o0m;p l3e2t0e d5
68); clipsToBounds = YES; hidden = YES; autoresize = RM+BM; gestureRecognizers = <NSArray: 0x7faa9bda1f00>; layer = <CALayer: 0x7faa9bd9e750>; contentOffset: {0, -64}; contentSize: {320, 0}>)
Optional(<UITableView: 0x7faa9c852000; frame = (0 0; 320 568); clipsToBounds = YES; autoresize = RM+BM; gestureRecognizers = <NSArray: 0x7faa9bda1f00>; layer = <CALayer: 0x7faa9bd9e750>; contentOffset: {0, -64}; contentSize: {320, 91}>)
Auction Latest : ViewWillAppear
task completed
Optional(<UITableView: 0x7faa9c852000; frame = (0 0; 320 568); clipsToBounds = YES; autoresize = RM+BM; gestureRecognizers = <NSArray: 0x7faa9bda1f00>; layer = <CALayer: 0x7faa9bd9e750>; contentOffset: {0, -64}; contentSize: {320, 91}>)
Auction Latest : ViewWillAppear
task completed
Optional(<UITableView: 0x7faa9c852000; frame = (0 0; 320 568); clipsToBounds = YES; autoresize = RM+BM; gestureRecognizers = <NSArray: 0x7faa9bda1f00>; layer = <CALayer: 0x7faa9bd9e750>; contentOffset: {0, -64}; contentSize: {320, 91}>)
PostData: &email=example.test@gmail.com&appid=9cdcf896d1f54c3c11b0d4839ce26775
Response code: 200
Response ==> {"status":"ok"}
Status:
Error:
Log Out SUCCESS
Auction Latest : ViewWillAppear
task completed
nil

任何想法?有什么建议吗?我留下了对我的问题的评论。希望得到这个帮助

1 个答案:

答案 0 :(得分:0)

更新那个菜单,你必须调用你已经采取该表视图的那个类的方法,为此你做了一件事, 将该类的对象创建到您想要更新的其他类中,然后通过该调用创建该类的方法,如...

[sliderpage viewWillAppear:YES];

这里的silderpage是菜单页面的对象....

我希望这对你有所帮助....