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

Posted

技术标签:

【中文标题】当我从另一个视图控制器调用时,为啥我的表视图为零?【英文标题】:iWhy my table view is nil when i called from another view controller?当我从另一个视图控制器调用时,为什么我的表视图为零? 【发布时间】:2015-04-06 11:15:19 【问题描述】:

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

这是我的幻灯片菜单控制器 (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】:

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

[sliderpage viewWillAppear:YES];

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

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

【讨论】:

嗯,如果你不介意,请迅速解释,因为我不知道你所说的任何事情。从你的解释看,我确实使用 AuctionLatestViewController 初始化了 refreshActionLatestController(见左侧菜单控制器的顶部)。当用户点击注销时,我在左侧菜单控制器上调用了类似“self.refreshActionLatestController?.viewWillAppear(true)”的视图控制器类。所以,这也没有解决。我更新了代码 对不起,我不太了解斯威夫特

以上是关于当我从另一个视图控制器调用时,为啥我的表视图为零?的主要内容,如果未能解决你的问题,请参考以下文章

添加注释以从另一个视图映射

为啥 UILable 在从另一个页面传递值之前不会显示?

从后台打开应用程序时不调用 ViewDidAppear

当我迅速从该视图控制器移动时,为啥我的 Collectionview 单元格没有显示?

如何正确初始化共享视图?

为啥我不能从另一个控制器中删除视图?