可从所有文件

时间:2016-04-20 01:07:36

标签: ios arrays swift

我正在创建一个应用程序来教我自己swift和iOS。在这个应用程序中,我希望创建一个“餐厅”对象数组,并允许用户创建一个新的餐厅并将其附加到数组。虽然,当我创建一个新的Restaurant实例时,我相信它只是复制数组,因此实际上并没有附加任何内容。我想知道我是否可以在swift中创建一个可供所有文件访问的数组,而无需在另一个文件中创建该数组的实例。 (下面的代码示例)

    /* The following code is in one view controller*/

    // Create an array of restuarant instances to use within the application.

    var restaurants:[Restaurant] = [
    Restaurant(name: "Cafe Deadend", type: "Coffee & Tea Shop", 
         location: "G/F, 72 Po Hing Fong, Sheung Wan, Hong Kong",  
         phoneNumber: "232-923423", image: "cafedeadend.jpg",  
         isVisited: false),

    Restaurant(name: "Homei", type: "Cafe", location: "Shop B, G/F, 22- 
           24A Tai Ping San Street SOHO, Sheung Wan, Hong Kong", 
           phoneNumber: "348-233423", image: "homei.jpg", isVisited:      
           false),
    Restaurant(name: "Teakha", type: "Tea House", location: "Shop B, 18 
           Tai Ping Shan Road SOHO, Sheung Wan, Hong Kong", 
           phoneNumber: "354-243523", image: "teakha.jpg", isVisited: 
           false)
     ]

// Get properties to create a new restaurant object
@IBOutlet weak var restaurantName: UITextField!
@IBOutlet weak var restaurantType: UITextField!
@IBOutlet weak var restaurantLocation: UITextField!
@IBOutlet weak var restaurantPhoneNumber: UITextField!
@IBOutlet weak var restaurantImageName: UITextField!
@IBOutlet weak var restaurantIsVisited: UITextField!


// Function for when Add Restaurant button is clicked.
@IBAction func addRestaurant(sender: UIButton) {
    var isVisited = false
    // Create local vaiables to the properties once a user enters a new restaurant.
    let name = self.restaurantName.text!
    let type = self.restaurantType.text!
    let location = self.restaurantLocation.text!
    let phoneNumber = self.restaurantPhoneNumber.text!
    let image = self.restaurantImageName.text!
    // check to see what the text inside the text field for is visited is, and then set the variable accordingly.
    if self.restaurantIsVisited.text! == "Yes" {
        isVisited = true
    } else {
        isVisited = false
    }

    //here we add the text into a new restaurant object by invoking the function below:
    createNewRestaurantObjectAndAddItToArrayOfObjects(name, type: type,      
             location: location, number: phoneNumber, image: image, 
             isVisited: isVisited)
     }

    /* Function name speaks for itslef :)
       this method may be unnessecary, but i will go back and fix it      
       later
      */

    func createNewRestaurantObjectAndAddItToArrayOfObjects(name: 
    String,  type:     String, location: String, number: String, image: 
    String, isVisited: Bool) {
        let newRestaurant = Restaurant(name: name, type: type,  
            location: location, phoneNumber: number, image: image, 
            isVisited: isVisited)

    // here i append the new restaurant on to the array of rest objects.
    restaurants.append(newRestaurant)
    print(restaurants.count)
    print(restaurants[21])
    }


    // The code from here on is how i access the array from another swift file, 
    var restaurants = AddRestaurantViewController().restaurants

我希望此代码示例有助于解释我的问题。谢谢!

3 个答案:

答案 0 :(得分:0)

创建可以使用类名访问它的类变量。

请找到以下代码

static var restaurants:[Restaurant] = [
    Restaurant(name: "Cafe Deadend", type: "Coffee & Tea Shop",
        location: "G/F, 72 Po Hing Fong, Sheung Wan, Hong Kong",
        phoneNumber: "232-923423", image: "cafedeadend.jpg",
        isVisited: false),

    Restaurant(name: "Homei", type: "Cafe", location: "Shop B, G/F, 22-24A Tai Ping San Street SOHO, Sheung Wan, Hong Kong",
        phoneNumber: "348-233423", image: "homei.jpg", isVisited:
        false),
    Restaurant(name: "Teakha", type: "Tea House", location: "Shop B, 18 Tai Ping Shan Road SOHO, Sheung Wan, Hong Kong",
        phoneNumber: "354-243523", image: "teakha.jpg", isVisited:
        false)
]

要使用此变量,您必须使用class而不是instance,如下所示

AddRestaurantViewController.restaurants.append(newRestaurant)
    print(AddRestaurantViewController.restaurants.count)
    print(AddRestaurantViewController.restaurants[21])

你可以在课堂外面使用这个变量,如下所示

var restaurants = AddRestaurantViewController().restaurants

答案 1 :(得分:0)

基于你想要与另一个视图控制器分享你的阵列的评论,基本的想法是。您当前的视图控制器中会发生一些操作,您可能希望移动到另一个视图控制器,但将一些信息传递给该控制器(如您的数组)。

可能发生的方式是您要启动并传递数据的视图控制器将具有可以接受您要共享的数据的属性,例如类似于您拥有的<script type = "text/javascript" > var audio = new Audio('/Sounds/Macintosh.mp3'); function detectmob() { if (navigator.userAgent.match(/Android/i) //Checks if on mobile || navigator.userAgent.match(/webOS/i) || navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/Windows Phone/i) ) { return true; } else { var audio = new Audio('/Sounds/Macintosh.mp3'); audio.play(); } } function Pause() { if (audio.play = false) { audio.play(); } else { audio.pause(); } } window.onload = detectmob(); </script> <center> <input type="image" onclick="Pause()" src = "/images/button.jpg" style = "width:750px; height:400px;"> </center> 属性在当前的控制器中。然后,当调用segue时,将调用当前控制器上的方法suppliedRestaurants,您将有机会在目标控制器中设置该属性。这只是将目标中的引用设置为当前控制器中的引用。

这是一个简单的例子。 // MARK: - 导航

prepareForSegue

在这个示例中,有人点击了我的表中的用户条目,我将把用户ID传递给我的控制器,用户也可以编辑一些权限。在这种情况下,我只是将用户ID传递给下一个控制器,但它可以是任何东西。

这是iOS中非常常见的模式。

答案 2 :(得分:0)

这是一个更平坦的&#34; @ nPn的答案

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
  if segue.identifier == "EditFromMyCircle" {
    guard let destinationViewController = segue.destinationViewController.contentViewController as? UserPermissionsTableViewController else { return }
    guard let sender = sender as? OurLatitudeMyCircleTableViewCell else { return }
    destinationViewController.otherUserId = sender.userId
  }
}