Swift xcode错误:线程1:EXC_BAD_ACCESS(代码= 2,地址= 0x7ff54b59ff8)

时间:2016-02-27 05:35:39

标签: ios xcode swift

我的项目应该创建一个包含动物名称列表的窗口,但是当用户选择一个名称(一行)时,用户就会被转移到另一个带有动物描述的窗口。

以下是出现错误的位置: enter image description here

这是Animal类(注意:此类中出现的错误)

import UIKit
class Animal
{
    var name: String
    var shortDescription: String
    var longDescription: String
    init(name: String, shortDescription: String, longDescription: String)
    {
        self.name = name
        self.shortDescription = shortDescription
        self.longDescription = longDescription
    }
    let animals = [
        Animal(name: "Cow", //THIS LINE IS THE ERROR: Thread 1: EXC_BAD_ACCESS (code=2, address=0x7ff54b59ff8)
            shortDescription: "Cattle",
            longDescription: "A cow is a mature female and bull of an adult male of a bovine family. A heifer is a female cow that hasn't had a calf yet. Cattle is the name for the whole cow family. THere are about 920 different breeds of cows in the world."),
        Animal(name: "Bird",
            shortDescription: "Usually small, has wings, feathers, and can fly.",
            longDescription: "A warm-blooded egg-laying vertebrate distinguished by the possession of feathers, wings, and a beak and (typically) by being able to fly."),
        Animal(name: "Dolphin",
            shortDescription: "A large fish",
            longDescription: "A small gregarious toothed whale that typically has a beaklike snout and a curved fin on the back. Dolphins have become well known for their sociable nature and high intelligence."),
        Animal(name: "Dog",
            shortDescription: "Man's best friend",
            longDescription: "A domesticated carnivorous mammal that typically has a long snout, an acute sense of smell, and a barking, howling, or whining voice. It is widely kept as a pet or for work or field sports."),
        Animal(name: "Zebra",
            shortDescription: "A horse with white and black stripes",
            longDescription: "An African wild horse with black-and-white stripes and an erect mane."),
        Animal(name: "Owl",
            shortDescription: "A large bird that usually comes out at night",
            longDescription: "A nocturnal bird of prey with large forward-facing eyes surrounded by facial disks, a hooked beak, and typically a loud call."),
        Animal(name: "Camel",
            shortDescription: "A horse-like animal that travels the deserts",
            longDescription: "A large, long-necked ungulate mammal of arid country, with long slender legs, broad cushioned feet, and either one or two humps on the back. Camels can survive for long periods without food or drink, chiefly by using up the fat reserves in their humps."),
        Animal(name: "Lizard",
            shortDescription: "A green animal that is very small and has four legs",
            longDescription: "A reptile that typically has a long body and tail, four legs, movable eyelids, and a rough, scaly, or spiny skin."),
        Animal(name: "Monkey",
            shortDescription: "A furry animal that climbs trees.",
            longDescription: "A small to medium-sized primate that typically has a long tail, most kinds of which live in trees in tropical countries."),
        Animal(name: "Jaguar",
            shortDescription: "A very fast animal with four legs and lots of fur",
            longDescription: "A large, heavily built cat that has a yellowish-brown coat with black spots, found mainly in the dense forests of Central and South America."),
        Animal(name: "Chicken",
            shortDescription: "A small legged animal with a red nose.",
            longDescription: "A domestic fowl kept for its eggs or meat, especially a young one."),
        Animal(name: "Mouse",
            shortDescription: "A very small creature with a tail.",
            longDescription: "a small rodent that typically has a pointed snout, relatively large ears and eyes, and a long tail.")]
}


Here is the AppDelegate class
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate
{
    let animals = [
        Animal(name: "Cow",
            shortDescription: "Cattle",
            longDescription: "A cow is a mature female and bull of an adult male of a bovine family. A heifer is a female cow that hasn't had a calf yet. Cattle is the name for the whole cow family. THere are about 920 different breeds of cows in the world."),
        Animal(name: "Bird",
            shortDescription: "Usually small, has wings, feathers, and can fly.",
            longDescription: "A warm-blooded egg-laying vertebrate distinguished by the possession of feathers, wings, and a beak and (typically) by being able to fly."),
        Animal(name: "Dolphin",
            shortDescription: "A large fish",
            longDescription: "A small gregarious toothed whale that typically has a beaklike snout and a curved fin on the back. Dolphins have become well known for their sociable nature and high intelligence."),
        Animal(name: "Dog",
            shortDescription: "Man's best friend",
            longDescription: "A domesticated carnivorous mammal that typically has a long snout, an acute sense of smell, and a barking, howling, or whining voice. It is widely kept as a pet or for work or field sports."),
        Animal(name: "Zebra",
            shortDescription: "A horse with white and black stripes",
            longDescription: "An African wild horse with black-and-white stripes and an erect mane."),
        Animal(name: "Owl",
            shortDescription: "A large bird that usually comes out at night",
            longDescription: "A nocturnal bird of prey with large forward-facing eyes surrounded by facial disks, a hooked beak, and typically a loud call."),
        Animal(name: "Camel",
            shortDescription: "A horse-like animal that travels the deserts",
            longDescription: "A large, long-necked ungulate mammal of arid country, with long slender legs, broad cushioned feet, and either one or two humps on the back. Camels can survive for long periods without food or drink, chiefly by using up the fat reserves in their humps."),
        Animal(name: "Lizard",
            shortDescription: "A green animal that is very small and has four legs",
            longDescription: "A reptile that typically has a long body and tail, four legs, movable eyelids, and a rough, scaly, or spiny skin."),
        Animal(name: "Monkey",
            shortDescription: "A furry animal that climbs trees.",
            longDescription: "A small to medium-sized primate that typically has a long tail, most kinds of which live in trees in tropical countries."),
        Animal(name: "Jaguar",
            shortDescription: "A very fast animal with four legs and lots of fur",
            longDescription: "A large, heavily built cat that has a yellowish-brown coat with black spots, found mainly in the dense forests of Central and South America."),
        Animal(name: "Chicken",
            shortDescription: "A small legged animal with a red nose.",
            longDescription: "A domestic fowl kept for its eggs or meat, especially a young one."),
        Animal(name: "Mouse",
            shortDescription: "A very small creature with a tail.",
            longDescription: "a small rodent that typically has a pointed snout, relatively large ears and eyes, and a long tail.")]
    var window: UIWindow?
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.
        return true
    }
    func applicationWillResignActive(application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(application: UIApplication) {
        // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let animal:Animal = animals[indexPath.row]
        let cell = tableView.dequeueReusableCellWithIdentifier("Animal name", forIndexPath: indexPath) as UITableViewCell
        /*var name: String
        var shortDescription: String
        var longDescription: String
        // Configure the cell...
        */
        cell.textLabel?.text = animal.name
        cell.detailTextLabel?.text = animal.shortDescription

        return cell
    }
}
    /*

    override func tableView(tableView: UITableView,
        didSelectRowAtIndexPath indexPath: NSIndexPath) {
            let title = "Wine List"
            let message = "You have selected \(wines[indexPath.row].name)"
            let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
            let okayAction = UIAlertAction(title: "Okay", style: .Default, handler: nil)
            alertController.addAction(okayAction)
            presentViewController(alertController, animated: true, completion: nil)
            self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
    }


    override func tableView(tableView: UITableView,
        accessoryButtonTappedForRowWithIndexPath indexPath: NSIndexPath) {
            let wine = wines[indexPath.row]
            let title = wine.name
            let message = wine.longDescription
            let alertController = UIAlertController(title: title, message: message, preferredStyle: .ActionSheet)
            let okayAction = UIAlertAction(title: "Okay", style: .Default, nil)
            alertController.addAction(okayAction)
            presentViewController(alertController, animated: true, completion: nil)
            self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
    }


    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the specified item to be editable.
        return true
    }



    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }
    }



    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }



    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the item to be re-orderable.
        return true
    }}

这是AnimalListTableViewController类

import UIKit
class AnimalListTableViewController: UITableViewController
{   var name: String
    var shortDescription: String
    var longDescription: String
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 12}
    override func prepareForSegue(segue: UIStoryboardSegue,
        sender: AnyObject?){
            if let detailViewController = segue.destinationViewController as? DetailViewController, let indexPath = self.tableView.indexPathForSelectedRow {
                detailViewController.animal = animals[indexPath.row]}}
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")}
    let animals = [
        Animal(name: "Cow",
            shortDescription: "Cattle",
            longDescription: "A cow is a mature female and bull of an adult male of a bovine family. A heifer is a female cow that hasn't had a calf yet. Cattle is the name for the whole cow family. THere are about 920 different breeds of cows in the world."),
        Animal(name: "Bird",
            shortDescription: "Usually small, has wings, feathers, and can fly.",
            longDescription: "A warm-blooded egg-laying vertebrate distinguished by the possession of feathers, wings, and a beak and (typically) by being able to fly."),
        Animal(name: "Dolphin",
            shortDescription: "A large fish",
            longDescription: "A small gregarious toothed whale that typically has a beaklike snout and a curved fin on the back. Dolphins have become well known for their sociable nature and high intelligence."),
        Animal(name: "Dog",
            shortDescription: "Man's best friend",
            longDescription: "A domesticated carnivorous mammal that typically has a long snout, an acute sense of smell, and a barking, howling, or whining voice. It is widely kept as a pet or for work or field sports."),
        Animal(name: "Zebra",
            shortDescription: "A horse with white and black stripes",
            longDescription: "An African wild horse with black-and-white stripes and an erect mane."),
        Animal(name: "Owl",
            shortDescription: "A large bird that usually comes out at night",
            longDescription: "A nocturnal bird of prey with large forward-facing eyes surrounded by facial disks, a hooked beak, and typically a loud call."),
        Animal(name: "Camel",
            shortDescription: "A horse-like animal that travels the deserts",
            longDescription: "A large, long-necked ungulate mammal of arid country, with long slender legs, broad cushioned feet, and either one or two humps on the back. Camels can survive for long periods without food or drink, chiefly by using up the fat reserves in their humps."),
        Animal(name: "Lizard",
            shortDescription: "A green animal that is very small and has four legs",
            longDescription: "A reptile that typically has a long body and tail, four legs, movable eyelids, and a rough, scaly, or spiny skin."),
        Animal(name: "Monkey",
            shortDescription: "A furry animal that climbs trees.",
            longDescription: "A small to medium-sized primate that typically has a long tail, most kinds of which live in trees in tropical countries."),
        Animal(name: "Jaguar",
            shortDescription: "A very fast animal with four legs and lots of fur",
            longDescription: "A large, heavily built cat that has a yellowish-brown coat with black spots, found mainly in the dense forests of Central and South America."),
        Animal(name: "Chicken",
            shortDescription: "A small legged animal with a red nose.",
            longDescription: "A domestic fowl kept for its eggs or meat, especially a young one."),
        Animal(name: "Mouse",
            shortDescription: "A very small creature with a tail.",
            longDescription: "a small rodent that typically has a pointed snout, relatively large ears and eyes, and a long tail.")]}

这是AppDelegate类

import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate
{
    let animals = [
        Animal(name: "Cow",
            shortDescription: "Cattle",
            longDescription: "A cow is a mature female and bull of an adult male of a bovine family. A heifer is a female cow that hasn't had a calf yet. Cattle is the name for the whole cow family. THere are about 920 different breeds of cows in the world."),
        Animal(name: "Bird",
            shortDescription: "Usually small, has wings, feathers, and can fly.",
            longDescription: "A warm-blooded egg-laying vertebrate distinguished by the possession of feathers, wings, and a beak and (typically) by being able to fly."),
        Animal(name: "Dolphin",
            shortDescription: "A large fish",
            longDescription: "A small gregarious toothed whale that typically has a beaklike snout and a curved fin on the back. Dolphins have become well known for their sociable nature and high intelligence."),
        Animal(name: "Dog",
            shortDescription: "Man's best friend",
            longDescription: "A domesticated carnivorous mammal that typically has a long snout, an acute sense of smell, and a barking, howling, or whining voice. It is widely kept as a pet or for work or field sports."),
        Animal(name: "Zebra",
            shortDescription: "A horse with white and black stripes",
            longDescription: "An African wild horse with black-and-white stripes and an erect mane."),
        Animal(name: "Owl",
            shortDescription: "A large bird that usually comes out at night",
            longDescription: "A nocturnal bird of prey with large forward-facing eyes surrounded by facial disks, a hooked beak, and typically a loud call."),
        Animal(name: "Camel",
            shortDescription: "A horse-like animal that travels the deserts",
            longDescription: "A large, long-necked ungulate mammal of arid country, with long slender legs, broad cushioned feet, and either one or two humps on the back. Camels can survive for long periods without food or drink, chiefly by using up the fat reserves in their humps."),
        Animal(name: "Lizard",
            shortDescription: "A green animal that is very small and has four legs",
            longDescription: "A reptile that typically has a long body and tail, four legs, movable eyelids, and a rough, scaly, or spiny skin."),
        Animal(name: "Monkey",
            shortDescription: "A furry animal that climbs trees.",
            longDescription: "A small to medium-sized primate that typically has a long tail, most kinds of which live in trees in tropical countries."),
        Animal(name: "Jaguar",
            shortDescription: "A very fast animal with four legs and lots of fur",
            longDescription: "A large, heavily built cat that has a yellowish-brown coat with black spots, found mainly in the dense forests of Central and South America."),
        Animal(name: "Chicken",
            shortDescription: "A small legged animal with a red nose.",
            longDescription: "A domestic fowl kept for its eggs or meat, especially a young one."),
        Animal(name: "Mouse",
            shortDescription: "A very small creature with a tail.",
            longDescription: "a small rodent that typically has a pointed snout, relatively large ears and eyes, and a long tail.")]
    var window: UIWindow?
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.
        return true
    }
    func applicationWillResignActive(application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(application: UIApplication) {
        // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let animal:Animal = animals[indexPath.row]
        let cell = tableView.dequeueReusableCellWithIdentifier("Animal name", forIndexPath: indexPath) as UITableViewCell
        /*var name: String
        var shortDescription: String
        var longDescription: String
        // Configure the cell...
        */
        cell.textLabel?.text = animal.name
        cell.detailTextLabel?.text = animal.shortDescription

        return cell
    }
}
    /*

    override func tableView(tableView: UITableView,
        didSelectRowAtIndexPath indexPath: NSIndexPath) {
            let title = "Wine List"
            let message = "You have selected \(wines[indexPath.row].name)"
            let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
            let okayAction = UIAlertAction(title: "Okay", style: .Default, handler: nil)
            alertController.addAction(okayAction)
            presentViewController(alertController, animated: true, completion: nil)
            self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
    }


    override func tableView(tableView: UITableView,
        accessoryButtonTappedForRowWithIndexPath indexPath: NSIndexPath) {
            let wine = wines[indexPath.row]
            let title = wine.name
            let message = wine.longDescription
            let alertController = UIAlertController(title: title, message: message, preferredStyle: .ActionSheet)
            let okayAction = UIAlertAction(title: "Okay", style: .Default, nil)
            alertController.addAction(okayAction)
            presentViewController(alertController, animated: true, completion: nil)
            self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
    }


    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the specified item to be editable.
        return true
    }



    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }
    }



    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }



    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the item to be re-orderable.
        return true
    }
*/

这是DetailViewController类

import UIKit


class DetailViewController: UIViewController
{
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var descriptionLabel: UILabel!
    var a = Animal?()
    var animal: Animal?



    override func viewWillAppear(animated: Bool)
    {
        titleLabel.text = a!.name
        descriptionLabel.text = a!.longDescription
    }



    override func viewDidLoad()
    {
        viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning()
    {
        didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }



}

这是故事板。

enter image description here

1 个答案:

答案 0 :(得分:6)

您可能想要Animal上的静态属性。

animals声明更改为:

static let animals = [...]

你想要访问那些动物阵列的任何地方,请使用:

Animal.animals

您遇到的问题是,当您创建动物时,它具有实例化更多动物(数组)的属性,并且每只动物实例化更多动物,依此类推,导致无限循环。