2015-08-20 31 views
1

我有一个视图控制器,它让用户输入一个特定的日期(对于一个闹钟),我希望这个闹钟在应用程序进入后台时运行,所以我想通过NSDate到一个在App Delegate中变量,最好的方法是什么?将数据传递给AppDelegate中的变量

我试图用这个

let appD = AppDelegate() 
    appD.dat = dueDatePicker.date 

,但它没有工作,一旦用户选择的日期和点击保存,视图控制器塞格斯到主视图控制器,

继承人的代码我已经在应用程序的委托运行:

var backgroundUpdateTask: UIBackgroundTaskIdentifier! 
    var dat:NSDate? 
func beginBackgroundUpdateTask() { 
    self.backgroundUpdateTask = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({ 
     self.endBackgroundUpdateTask() 
    }) 
} 

func endBackgroundUpdateTask() { 
    UIApplication.sharedApplication().endBackgroundTask(self.backgroundUpdateTask) 
    self.backgroundUpdateTask = UIBackgroundTaskInvalid 
} 

func doBackgroundTask() { 
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { 
     self.beginBackgroundUpdateTask() 

     // Do something with the result. 
     let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext 
     let entityDescription = NSEntityDescription.entityForName("TaskModel", inManagedObjectContext: managedObjectContext!) 
     let addTaskVC:AddTaskViewController = AddTaskViewController() 


     println(self.dat) 
     let calendar = NSCalendar.currentCalendar() 
     let comp = calendar.components(NSCalendarUnit.CalendarUnitSecond, fromDate: date) 


     let seconds = Double(comp.second) 
     println(seconds) 
     var timer = NSTimer.scheduledTimerWithTimeInterval(seconds, target: self, selector: "update", userInfo: nil, repeats: false) 
     NSRunLoop.currentRunLoop().addTimer(timer, forMode: NSDefaultRunLoopMode) 
     NSRunLoop.currentRunLoop().run() 


     // End the background task. 
     self.endBackgroundUpdateTask() 
    }) 
} 

我的问题是,可变DAT一直显示为零导致应用程序崩溃,一旦进入后台模式的值, Ÿ信息表示赞赏

回答

1

你不能为了让您的应用程序代理使用,创造的AppDelegate

一个实例:

let delegate = UIApplication.sharedApplication().delegate 
0

常用的语法来引用AppDelegate的实例

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate 

永远不要在Interface Builder中调用类的初始化器(已经设计(和实例化))。

0

试试这个,

1)AppDelegate.swift初始化变量

例如:

var data:NSString!="" 

2)在你的ViewController创建的AppDelegate实例

例如:

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

3)通过appDelegate变量的init值传递数据。

例如:

appDelegate.data="your_Sending_Data_to_AppDelegate"