2016-02-27 263 views
0

我的項目應該創建一個帶有動物名稱列表的窗口,但是當用戶選擇一個名稱(一行)時,運輸到另一個窗口並描述動物。Swift xcode error:線程1:EXC_BAD_ACCESS(code = 2,address = 0x7ff54b59ff8)

這裏是出現在誤差: enter image description here

這裏是動物類(注意:錯誤出現在此CLASS)

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

回答

2

你可能想在Animal的靜態屬性。

更改animals宣言是:無論你要訪問的動物陣列

static let animals = [...] 

,使用此:

Animal.animals 

您遇到的問題是,當你創建一個動物,它具有實例化更多動物(該陣列)的屬性,並且每個動物實例化更多動物等等,導致無限循環。

+0

謝謝,現在錯誤消失了。 – David

相關問題