发布于 2015-12-28 00:38:42 | 194 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的Swift教程,程序狗速度看过来!

Swift编程语言

SWIFT,苹果于2014年WWDC(苹果开发者大会)发布的新开发语言,可与Objective-C*共同运行于Mac OS和iOS平台,用于搭建基于苹果平台的应用程序。


在swift中,要使用定时器就需要用到对象NSTimer。通过NSTimer的实例化后,就可以调用fire方法来启用了。

NSTimer有2个构造函数

 
init(timeInterval ti: NSTimeInterval, invocation: NSInvocation!, repeats yesOrNo: Bool) -> NSTimer
 
init(timeInterval ti: NSTimeInterval, target aTarget: AnyObject!, selector aSelector: Selector, userInfo: AnyObject!, repeats yesOrNo: Bool) -> NSTimer

通过我的实践后,发现这2个构造函数都是假的,基本上不能使用。第一个构造函数的invocation参数貌似swift还没有实现(xCode6 beta)通过mac+left click点进去后,里面啥也没有。到是在stackoverflow上看到有大神使用的,没有尝试:

NSMethodSignature *sgn = [self methodSignatureForSelector:@selector(onTick:)];
NSInvocation *inv = [NSInvocation invocationWithMethodSignature: sgn];
[inv setTarget: self];
[inv setSelector:@selector(onTick:)];
 
NSTimer *t = [NSTimer timerWithTimeInterval: 1.0
                      invocation:inv
                      repeats:YES];

显然在swift中,还没有NSInvocation.invocationWithMethodSignature方法的实现。

第二个构造函数,通过它可以实例化NSTimer对象,但只能触发一次。之后就没用了,貌似repeats的参数是没有作用的。

1
2
var timer = NSTimer(1.0, target: self, selector: "timerFireMethod:", userInfo: nil, repeats:true);
timer.fire()

后来看到网上大家都使用的静态函数的形式实例化,也尝试了一下,竟然成功了:

 
func doTimer(){
    var timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "timerFireMethod:", userInfo: nil, repeats:true);
    timer.fire()
}
func timerFireMethod(timer: NSTimer) {
    var formatter = NSDateFormatter();
    formatter.dateFormat = "MM/dd/yyyy HH:mm:ss"
    var strNow = formatter.stringFromDate(NSDate())
    txta.text  = "\(strNow)"
}

程序的目的就是在view上的label中实时显示当前的时间。

总结:

1、NSTimer只能使用静态函数来实例化该对象

2、使用静态函数来实例化对象的时候,竟然需要传一个实例对象的方法(通过selector),这个感觉有些违背面向对象的思想的。任何对象的成员的访问都需要通过实例化对象来调用。swift中有全局函数,想想也释然了,毕竟他是一门刚出来的语言还是需要时间沉淀的。

3、在模拟器中,运行10分钟,程序所使用的memory,从12.0MB上升到了12.5MB。感觉对内存的要求还是比较高的,不知道有没有其它更好的方法实现。



最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务