2015年12月

AppDelegate.swift文件

记录下

//  AppDelegate.swift
//导入UIKit库
import UIKit
//当前app的入口点
@UIApplicationMain
//当前UIApplication的委托类,继承自UIResponder(响应用户的交互行为),实现协议UIApplicationDelegate
class AppDelegate: UIResponder, UIApplicationDelegate {
    //当前程序的窗口
    var window: UIWindow?

    //当前App夹在成功,调用这个
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.
        return true
    }
    //app在从当前激活状态变成不激活状态,调用这个方法,例如在app运行过程中接到电话
    func applicationWillResignActive(application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    }
    //app进入到后台,调用这个方法,例如在app使用中按 home 键
    func applicationDidEnterBackground(application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }
    //从后台将要转入前台的时候调用,比如双击 home 键,单击 app 图标
    func applicationWillEnterForeground(application: UIApplication) {
        // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    }
    //本来在后台,现在即将转向前台,并且即将成为激活状态时调用
    func applicationDidBecomeActive(application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }
    //程序退出的时候调用
    func applicationWillTerminate(application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }


}

swift使用第三方开源库

参考网址 文章网址
我使用的Workspace的方式引入的
1.创建Workspace,名称随意,我这里的是 DemoAppWorkespace
在xcode中创建即可
2.在workespace中创建自己的项目
DemoAppWorkspace中创建项目DemoApp
3.下载第三方库,这里以SwiftyJSON库为例
用git下载即可
git clone https://github.com/SwiftyJSON/SwiftyJSON.git
4.引入第三方库
在文件夹中打开下载下来的文件,会看到以.xcodeproj结尾的文件,比如这个库的就是SwiftyJSON.xcodeproj,直接拖到DemoAppWorkespace中即可
5.为App添加依赖
DemoAppGenral选项卡中,添加Linked Frameworks and Libraries,在弹出的对话框中选择要引入的库,我这里是SwiftyJSON的ios版本
6.添加头文件
DemoApp中添加头文件,并引入

#import <SwiftyJSON/SwiftyJSON.h>

给控件绑定事件函数的时候,报错

在手动给控件添加事件的时候,报错
代码如下

class ViewController: UIViewController {

    @IBOutlet weak var button: UIButton!
    @IBOutlet weak var lable: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        button.addTarget(self, action: "buttonDown:", forControlEvents: .TouchDown)
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    func buttonDown(sender:AnyObject)
    {
        lable.text = "哈哈哈,来个hellow,world"
    }
}

报错如下

fatal error: unexpectedly found nil while unwrapping an Optional value

后来把控件都删除,重新拖一下就好了。。。。

利用NSObject实现观察者模式(KVO模式)

类定义

class huofu:NSObject
{
    dynamic var danchaofan = ""
    func update(status:String)
    {
        danchaofan = status
    }
}
class xiaohuoban:NSObject {
    init(objectToObserver:AnyObject) {
        super.init()
        //添加传递进来的类的观察者
        objectToObserver.addObserver(self, forKeyPath: "danchaofan", options: .New, context: &myContext)
    }
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]!, context: UnsafeMutablePointer<Void>) {
        if context == &myContext
        {
            print("\(change![NSKeyValueChangeNewKey])")
        }
    }
}

运行代码

let chaoge:huofu = huofu()
let huoban:xiaohuoban = xiaohuoban(objectToObserver: chaoge)
chaoge.update("更新1")
chaoge.removeObserver(huoban, forKeyPath: "danchaofan")

上面这样,可以正常运行,输出是正确的,但是之后会报错

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'An instance 0x7fdad1c0d270 of class CoreDataTest.huofu was deallocated while key value observers were still registered with it. Current observation info:

大概就是因为被观察的已经被回收了,但是观察者依然存在
改成下面就ok了

let chaoge:huofu = huofu()
let huoban:xiaohuoban = xiaohuoban(objectToObserver: chaoge)
chaoge.update("更新1")
chaoge.removeObserver(huoban, forKeyPath: "danchaofan")

swift使用CoreData增删改查

在新建项目的时候勾选 Use Core Data,在项目地下就会出现 以 .xcdatamodeld`结尾的文件,然后再里面可以新建托管对象模型(也称为实体),实体属性之类的,百度一下就可以搜索到 还有在AppDelegate.swift文件也已经生成了一些属性和方法,通过调用这些方法来实现增删改查 新建好实体之后,就可以生成托管对象,可以直接通过xcode生成Editor>Create NSManagedObject Sub...`然后选择下数据模型,要生成的实体,语言之类的信息,就ok了,
代码部分

//给实体增加新的托管对象,as关键字之前执行完会返回NSManagedObject对象,用 as! 关键字转换成 book 对象方便之后的赋值
var object:Book = NSEntityDescription.insertNewObjectForEntityForName("Book", inManagedObjectContext: self.managedObjectContext) as! Book
//赋值
object.name = "aaaa"
object.author = "aaaaa"
//保存,这个执行来就保存到文件中了
self.saveContext()

//通过实体名获取请求对象
let request = NSFetchRequest(entityName: "Book")
//指定查询条件
let predicate = NSPredicate(format: "%K != %@", "name","aaa")
//设置请求对象查询条件
request.predicate = predicate
//查询,因为 executeFetchRequest 方法是一个 throwing函数 所以用 try? 关键字,如果抛出异常的话会返回 nil,成功的话会返回一个对象数组 //转换成book对象数组,方便之后显示
let result = (try? self.managedObjectContext.executeFetchRequest(request)) as! [Book]
print(result)
//输出 "Optional("aaaa")"
print(result[0].name)


//获取请求对象
let request = NSFetchRequest(entityName: "Book")
//设置查询条件
let predicate = NSPredicate(format: "%K != %@", "name","sadasd")
//设置请求查询条件
request.predicate = predicate
//查询
if let result = try? self.managedObjectContext.executeFetchRequest(request)
{
    //循环查询结果数组
    for resultTemp in result
    {
    //打印实体值
    print((resultTemp as! Book).author)
    //判断是否是正确的对象
    if resultTemp is NSManagedObject
        {
            //修改值
            resultTemp.setValue("root", forKey: "author")
        }
    }
}
//上面的只是修改,并买油保存,这里执行保存,就改变了持久化数据的内容了
self.saveContext()

let request = NSFetchRequest(entityName: "Book")
let predicate = NSPredicate(format: "%K != %@", "name","asdasd")
request.predicate = predicate
if let result = (try? self.managedObjectContext.executeFetchRequest(request)) as? [NSManagedObject]
{
    //输出查询结果,查看删除是否有效
    print(result)
    for resultValue in result
    {
        if resultValue is NSManagedObject
        {
            self.managedObjectContext.deleteObject(resultValue)
        }
    }
}
self.saveContext()