2018-07-27 18:19:28 PrecipitantPan 阅读数 161

    swift存储数据使用core data,它是一套ORM框架,苹果力荐,但是性能不及sqlite,而且除了真tm复杂我也没看到有什么亮点,不过多学点总还是好的,黑人问号。

    Xcode提供一套可视化生成Entity,但是如果按照教程去做,自动使用默认的Class生成会报错,在YourEnityproperties.swift加上@obj或者直接选none生成,手撸也不费事的

    可以自己封装一下对context使用,注意container的名字需要修改,改成当前工程名,否则会抱实体不对应的错

import Foundation
import CoreData

class DataBase {
    
    static let shared = DataBase()
    private init() {
        
    }
    
    // MARK: - Core Data stack
    
    lazy var persistentContainer: NSPersistentContainer = {
        /*
         The persistent container for the application. This implementation
         creates and returns a container, having loaded the store for the
         application to it. This property is optional since there are legitimate
         error conditions that could cause the creation of the store to fail.
         */
        let container = NSPersistentContainer(name: "PFReminder")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                
                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()
    
    // MARK: - Core Data Saving support
    
    func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }
}

    个人吐槽的是这玩意儿的CURD确实糟糕...尤其是删,改...

func selectAll() -> [Notification]? {
        let managedObjectContext = db.persistentContainer.viewContext
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Notification")
       
        do {
            let fetchedResults = try managedObjectContext.fetch(fetchRequest) as? [Notification]
            return fetchedResults
        } catch {
            fatalError("获取失败")
        }
    }
    
    func saveNotification(title: String, body: String) {
        let date = DateUtil().getCurentDate()
        let managedObjectContext = db.persistentContainer.viewContext
       
        let entity = NSEntityDescription.entity(forEntityName: "Notification", in: managedObjectContext)
        let notification = NSManagedObject(entity: entity!, insertInto: managedObjectContext)
        
        notification.setValue(date, forKey: "id")
        notification.setValue(title, forKey: "title")
        notification.setValue(body, forKey: "body")
        
        do {
            try managedObjectContext.save()
        } catch  {
            fatalError("无法保存")
        }
        
        notifications.append(notification)
    }
    

 

2017-10-09 17:43:12 m0_38016385 阅读数 298

Swift Core Data

首先需要创建一个模版,进去“file”->“new”->”file”->”Core Data”->”Data Model”。

然后点击右下角的“add entity”。
这里写图片描述

在Xcode里面这个Entity会变成一个NSMangedObject的一个实体。Xcode的数据库是基于SQL的,所以每一个entity会有属性、关系以及fetched properties(用于搜索?)。

可以通过NSMangedObject的两个函数来更改属性的值。

创建关系

进入视图显示模式,ctrldrag两个entity。然后修改两个relations的名字。
这里写图片描述

然后可以修改它们n对n的约束(type)。

这里写图片描述

这样子会把tweets这一个关系变成NSSet。

在代码中使用

在代码中使用这些数据库需要使用NSManagedObjectContext。

在创建开始的项目的时候,如果选择了“Use Core Data”,那么Xcode会自动帮我们创建一些方法(在AppDelegate)。当然也可以我们自己创建UIManagedDocument。

创建代码
首先为他们创建subclass。
这里写图片描述

记得要选择swift。

不过创建的时候出现了错误提示,要解决这个问题可以参考这里

插入行至数据库

NSEntityDescription.insertNewObjectForEntityForName("Tweet", inManagedObjectContext: moc)

这里写图片描述

访问某一行的属性(列)

func valueForKey(String) -> AnyObject?
func setValue(AnyObject?, forKey: String )

保存

context.save()

但是这个方法有一个问题,就是可能会抛出错误,我们必须学习一下swift中错误抛出的处理方式。

删除

mangedObjectContext.deleteObject(tweet)

搜索
使用NSFetchRequest来进行。你需要规定想抓取的Entity,以及抓取的规模和限制。

同时也需要规定返回的string的排序方式(使用NSSortDescripitor)。
这里写图片描述

NSPredicate则是规定我们需要什么,注意其中的%@有点像printf里的%f。
这里写图片描述

上面的图片返回的是joe在aDate后创建的tweets以及screenName是CS193p的tweeter。

例子
这里写图片描述
这里写图片描述

Thrown Errors

do {
    try context.save()
} catch let error {
    //里面会有NSError,它提供一些方法可以处理这些错误。 
}

UITableView和Core Data的交互

因为大量的数据非常适合使用Table View来展示,所以xcode直接提供了一个NSFetchedResultsController类来实现。它可以总是和数据库同步。
这里写图片描述
这里写图片描述

创建一个NSFetchedResultsController的方法:
这里写图片描述

2017-08-23 16:23:20 tongwei117 阅读数 270
import UIKit

extension Date
{
    static func nowTime(_ dateFormat : String = "YYYY-MM-dd HH:mm:ss")->String{
        let formatter = DateFormatter.init();

        formatter.dateFormat = dateFormat;

        let date = Date.init();

        return formatter.string(from: date);
    }
}
2018-05-04 10:06:25 yingBi2014 阅读数 10343
let str:String = "意大利"
//字符串转Data
let data = str.data(using: String.Encoding.utf8)
//Data转字符串
let newStr = String(data: data!, encoding: String.Encoding.utf8)
print("data=" , data!  , "\n" ,  "newStr=" , newStr!)

输出结果

data= 9 bytes 
newStr= 意大利

2016-01-02 17:37:16 u013626773 阅读数 363

*An NSArray is heterogeneous, meaning that it can contain Cocoa objects of different types. Swift arrays are homogeneous, meaning that each Swift Array is guaranteed to contain only one type of object. 

However, you can still define a single Swift Array so it stores various types of Cocoa objects by specifying that the one type is AnyObject, since every Cocoa type is also a subtype of this. 


*Dictionaries are strongly typed, and you must have known key and value types. NSDictionary objects are able to take any NSObject as a key and store any object as a value.


*Note that subscripting syntax on dictionaries returns an optional. If the dictionary doesn't contain a value for a particular key, the optional is nil; if it does contain a value for that key you could get the wrapped value.

if let ellensCat = cats["Ellen"] {
	println("Ellen's cat is named \(ellensCat).")
} else {
	println("Ellen's cat's name not found!")
}

Because of that, it's a good idea to use the if let optional-unwrapping syntax to access values in a dictionary.


*Swift sets are type-specific -- all the items in a Swift Set must be of the same type.


*Creating Swift dictionaries is significantly slower than creating NSMutableDictionaries -- but both degrade at roughly the same O(n) rate.


*Set creation is considerably slower -- that's the price you pay for checking if every single item in a data structure is unique. 


*Removing and looking up are both around O(1) performance degradations across Swift and Foundation. This is largely because set structures use hashes to check for equality, and the hashes can be calculated and stored in sorted order. This makes set lookup considerably faster than array lookup.


*NSCountedSet tracks how many times you've added an object to a mutable set. It inherits from NSMutableSet, so if you try to add the same object again, it's only in the set once. 


*NSOrderedSet inherits from NSObject.


*You can use ordered sets as an alternative to arrays when element order matters and performance while testing whether an object is contained in the set is a consideration -- testing for membership of an array is slower than testing for membership of a set. 


*An NSIndexSet is an immutable collection of unique unsigned integers intended to represent indexes of an array. 


swift data 转byte

阅读数 1311

Swift使用CoreData

阅读数 711

没有更多推荐了,返回首页