如何从一个从另一个类中获取变量的类访问变量?

时间:2016-08-07 17:13:55

标签: swift oop

我正在尝试获取SpecialFood类中的成分名称(FoodName)。膳食类有一个属性膳食成分,其中包含成分对象。

现在在表格视图中,我试图在mealingredients中引用foodName,但是,它没有找到foodName,因为它指的是SpecificFood而不是meal类。我在一个单独的模型类中将所有内容和成分的名称输入到不同的食物中。

如果有更好的方法,那么请告诉我,因为我是swift和编程的新手。

非常感谢任何帮助。

5px

我已经引用了顶部的所有不同类;

let meal = self.selectedMeal

        let ingredientTitle = meal?.mealIngredients[indexPath.row].FoodName

        cell.textLabel?.text = String(ingredientTitle)

        return cell

我的餐饮课程是这样的;

 var myMeals:Array = [Meal]()
    var meals:[Meal] = [Meal]()
    var ingredients:[SpecificFood] = [SpecificFood]()

My SpecificFood类是这样的;

class Meal: NSObject {



    var mealTitle:String = ""
    var mealID:String = ""
    // var mealIngredients:NSArray = [NSObject]()
    var mealIngredients:NSArray = [SpecificFood]()

}

然后我的模型就是这样; (我已经采取了一些其他的食物和成分,但这给了主人。

class SpecificFood: NSObject {

    var foodName = ""
    var foodGroup = ""

}

前两行代码引用了带有tableView的类。除了class MealModel: NSObject { var ingredients:[SpecificFood] = [SpecificFood]() func getMeals() -> [Meal] { var allFoods = [SpecificFood]() let meat = String() let chicken = SpecificFood() let rice = SpecificFood() // Assign properties of the SpecificFoods chicken.foodName = "Chicken" chicken.foodGroup = meat // Add foods to my food array allFoods.append(chicken) // Create a meal objects var meal1 = Meal() // Assign properties meal1.mealIngredients = [chicken, rice, tomatoeSauce]

之外没有其他代码

2 个答案:

答案 0 :(得分:0)

没有看到你的类变量就有点难了......我将发布这个通用的例子:

class firstViewController: UIViewController {
    var someVariable: SomeType = someValue
    var someVariable2: SomeType = someValue

    init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }
}

然后实例化视图:

var myCustomViewController: firstViewController = firstViewController(nibName: nil, bundle: nil)
var variable = myCustomViewController.someVariable
var variable2 = myCustomViewController.someVariable2

答案 1 :(得分:0)

如果你有

meal1.mealIngredients = [chicken, rice, tomatoeSauce]
然后,您可以访问鸡的名称和食物组:

meal1.mealIngredients[0].foodName   // Chicken
meal1.mealIngredients[0].foodGroup   // meat

您可能需要考虑使用结构而不是类(除非您已经使用了继承)。

struct SpecificFood {
    var foodName = ""
    var foodGroup = ""
}

struct Meal {
    var mealTitle:String = ""
    var mealID:String = ""
    var mealIngredients: [SpecificFood]
}

您的代码变为:

let chicken = SpecificFood(foodName: "Chicken", foodGroup: "meat")
var meal1 = Meal(mealTitle: "Chicken and Rice", mealID: "45634", mealIngredients: [])

并使用点(。)语法访问属性。