tableview商店失去对ViewDidLoad嵌套可选展开的引用

时间:2016-07-04 11:49:08

标签: json swift reference tableview optional

我正在尝试解析一些天气数据,但我遇到了一个问题。我在一个数组中创建了一个默认值,为用户在表视图中提供了一个虚拟位置和值。使用下面我尝试用于实际数据的相同代码解包此值。它适用于虚拟值,可以轻松找到locationStore,但是当我从具有已解析数据的视图加载时,locationStore在调试器中显示为nil。我不知道如何解决这个问题,所以非常感谢任何帮助。

class LocationWeatherViewController: UITableViewController{

var locationStore: LocationStore!
var imageStore: ImageStore!
var newLocation: Location!
var locationCreated : NSMutableArray = NSMutableArray( array: ["Test ", 0, 0.0, 0.0 , 0.0]) 

override func viewDidLoad() {
    super.viewDidLoad()
    print(locationCreated.count)
    if let locationName = locationCreated[0] as? String {
        print(locationName)
        if let currentTemp = locationCreated[2] as? Double{
            print(currentTemp)
            if let zip32 = (locationCreated[1] as? Int){
                let zip = Int64(zip32)
                print(zip)
                if let xCrd = locationCreated[3] as? Double{
                    print(xCrd)
                    if let yCrd = locationCreated[4] as? Double{
                        print(yCrd)
                        newLocation = locationStore.createLocation(false, location: locationName, currentTemp: currentTemp, zipCode: zip, xCord: xCrd, yCord: yCrd)
                        if let index =  locationStore.allLocations.indexOf(newLocation){
                            let indexPath = NSIndexPath(forRow: index, inSection: 0)
                            tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
                        }

                    }
                }
            }
        }
    }
}


func createLocation(random: Bool, location: String, currentTemp: Double, zipCode: Int64, xCord: Double, yCord: Double ) -> Location{
    if !random{

        let newLocation = Location(random: false, locationNme: location, currentTmperature: currentTemp, locationZpCode: zipCode, xCrd: xCord, yCrd: yCord)
        allLocations.append(newLocation)
        return newLocation

    }

LocationStore:

    let newLocation = Location(random: true, locationNme: location, currentTmperature: currentTemp, locationZpCode: zipCode, xCrd: xCord, yCrd: yCord)
    allLocations.append(newLocation)

    return newLocation
}

位置:

init( locationName: String, currentTemperature: Double, locationZipCode: Int64, xCord: Double, yCord: Double){
    self.locationName = locationName
    self.currentTemperature = currentTemperature
    self.locationZipCode = Int64(locationZipCode)
    self.xCord = xCord
    self.yCord = yCord
    self.itemKey = NSUUID().UUIDString


    super.init()

}

convenience init( random:Bool = false, locationNme: String, currentTmperature: Double, locationZpCode: Int64, xCrd: Double, yCrd: Double ){
    if random {
        let locations = ["Louisville", "Gainesville", "Austin", "San Francisco"]
        //38.2527, 85.7585
        //29.6516, 82.3248
        // 30.2672, -97.7431
        // 37.7749, -122.4194
        let xCords = [38.2527, 29.6516, 30.2672, 37.7749 ]
        let yCords = [-85.7585, -82.3248, -97.7431, -122.4194 ]
        let zips = [40217, 32608, 77878, 46454]
        let temps = [76.0, 101.3, 95.4, 68.5]
        var idx = arc4random_uniform(UInt32(locations.count))
        let randomLocation = locations[Int(idx)]
        let randomLocationxCord = xCords[Int(idx)]
        let randomLocationyCord = yCords[Int(idx)]
        let randomZip = zips[Int(idx)]
        idx = arc4random_uniform(UInt32(temps.count))
        let randomTemp = temps[Int(idx)]

        self.init ( locationName: randomLocation, currentTemperature: randomTemp, locationZipCode: Int64(randomZip), xCord: randomLocationxCord, yCord: randomLocationyCord)

    }
    else{

        self.init( locationName: locationNme, currentTemperature: currentTmperature, locationZipCode: locationZpCode, xCord: xCrd, yCord: yCrd)
    }
}

APIFinder:

 func useAPI(zipCode: Int) -> NSArray{

    let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())

    let locationURL = NSURL( string: "http://api.openweathermap.org/data/2.5/forecast/city?zip=\(zipCode),us&APPID=74b78f4effe729b2a841cb35e3862d85")
    let request = NSURLRequest(URL: locationURL!)
    let task = session.dataTaskWithRequest(request) {
        (data,response, error) -> Void in

        if let locationData = data {
            if let jsonString = NSString( data:locationData,encoding: NSUTF8StringEncoding){
                let data = jsonString.dataUsingEncoding(NSUTF8StringEncoding)
                do {
                    let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as! [String: AnyObject]
                    if let city = json["city"]{
                        if let name = city["name"]{
                            self.locationArray[0] = name!
                            self.locationArray[1] = zipCode

                        }
                        if let coord = city["coord"]{
                            if let xCord = coord!["lat"]{
                                self.locationArray[3] = xCord!
                            }
                            if let yCord = coord!["lon"]{
                                self.locationArray[4] = yCord!
                            }
                        }

                    }
                    if let list = json["list"]{
                        if let main = list[0]["main"]{
                            if let temp = main!["temp"]{
                                self.locationArray[2] = temp!
                            }
                        }
                    }

                } catch let error as NSError {
                    print("Failed to load: \(error.localizedDescription)")
                }

            }
        }
        else if let requestError = error {
            print("Error fetching weather data: \(requestError)")
        }
        else {
            print("Unexpected error with request")
        }


    }
    task.resume()

    return locationArray


}

输出:

5

测试

0.0

0

0.0

0.0

5

哈特福德

295.54

42328

37.45116

-86.909157

致命错误:在解包可选值时意外发现nil

(lldb)

解决:

问题是我需要在segue中的视图之间传递LocationStore。一旦得到答案就会出现这样一个愚蠢的问题。 感谢您的所有帮助和建议。

0 个答案:

没有答案