我意识到每个类至少需要一个指定的初始化程序.我猜这是关键?
顺便说一下,我的“saveSession()到达”print语句在使用sim时登录到控制台,但在我使用设备时没有.即使使用设备,所有其他打印语句也会登录到控制台.有点奇怪.
我在初始化时的尝试会抛出各种错误,例如:
1.fatal error: use of unimplemented initializer ‘init()’ for class ‘DashboardController’
2.Missing argument for parameter ‘context’ in call
Dashboard.swift
class DashboardController: WKInterfaceController { @IBOutlet var timerLabel: WKInterfaceTimer! @IBOutlet weak var milesLabel: WKInterfaceLabel! // var wSM: WorkoutSessionManager //init(wSM: WorkoutSessionManager) { // self.wSM = wSM // super.init() // } override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) addMenuItemWithItemIcon(.Accept,title: "Save",action: #selector(DashboardController.saveSession)) } override func willActivate() { super.willActivate() print("Dashboard controller reached") } func saveSession() { //wSM.saveWorkout() print("saveSession() reached") }
WorkoutSessionManager.swift
class WorkoutSessionContext { let healthStore: HKHealthStore let activityType: HKWorkoutActivityType let locationType: HKWorkoutSessionLocationType init(healthStore: HKHealthStore,activityType: HKWorkoutActivityType = .Other,locationType: HKWorkoutSessionLocationType = .Unknown) { self.healthStore = healthStore self.activityType = activityType self.locationType = locationType } } protocol WorkoutSessionManagerDelegate: class { // ... protocol methods } class WorkoutSessionManager: NSObject,HKWorkoutSessionDelegate { let healthStore: HKHealthStore let workoutSession: HKWorkoutSession init(context: WorkoutSessionContext) { self.healthStore = context.healthStore self.workoutSession = HKWorkoutSession(activityType: context.activityType,locationType: context.locationType) self.currentActiveEnergyQuantity = HKQuantity(unit: self.energyUnit,doubleValue: 0.0) self.currentDistanceQuantity = HKQuantity(unit: self.distanceUnit,doubleValue: 0.0) super.init() self.workoutSession.delegate = self } func saveWorkout() { guard let startDate = self.workoutStartDate,endDate = self.workoutEndDate else {return} // ...code...