[IOS]Core Data简单实例(使用Xcode7)

Core Data简单实例

Core Data原理

Core Data是一个模型层的技术。Core Data帮助你建立代表程序状态的模型层。Core Data也是一种持久化技术,它能将模型对象的状态持久化到磁盘,但它最重要的特点是:Core Data不仅是一个加载、保存数据的框架,它还能和内存中的数据很好的共事。

创建属性列表

这里写图片描述

这里需要注意,名字都是键值,在后面的代码中要进行索引。

代码

//
//  TableViewController.swift
//  Hitlist
//
//  Created by 颜泽鑫 on 4/13/16.
//  Copyright © 2016 颜泽鑫. All rights reserved.
//

import UIKit
import CoreData

class TableViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
    }


    override func viewDidAppear(animated: Bool) {
        // 获取core data 的代理。
        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

        let managerObjectContext = appDelegate.managedObjectContext

        // 2 建立一个获取的请求
        let fetchRequest = NSFetchRequest(entityName: "Person")

        // 3 执行请求
        do {
            let fetchedRequest = try managerObjectContext.executeFetchRequest(fetchRequest)
            let result = fetchedRequest as! [NSManagedObject]
            people = result
            self.tableView.reloadData()
        } catch {
            print("error")
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    @IBAction func AddName(sender: AnyObject) {
        let alertController = UIAlertController(title: "Add a names?", message: nil, preferredStyle: UIAlertControllerStyle.Alert)
        let YesAction = UIAlertAction(title: "Yes", style: UIAlertActionStyle.Default) { (action : UIAlertAction) -> Void in
            let textField = alertController.textFields![0] as UITextField
            self.saveName(textField.text!)
            // 重新加载。
            // self.tableView.reloadData()
            let indexPath = NSIndexPath(forItem: self.people.count - 1, inSection: 0)
            self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
        }
        let CancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)
        alertController.addTextFieldWithConfigurationHandler { (UITextField) -> Void in

        }
        alertController.addAction(YesAction)
        alertController.addAction(CancelAction)
        self.presentViewController(alertController, animated: true, completion: nil)
    }
    // core data object
    // shape-shifted!
    // 这里面可以存储一切空间类型。
    var people = [NSManagedObject]()

    func saveName(text : String) {
        // 获取core data 的代理。
        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

        let managerObjectContext = appDelegate.managedObjectContext

        let entity = NSEntityDescription.entityForName("Person", inManagedObjectContext: managerObjectContext)

        let person = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managerObjectContext)
        person.setValue(text, forKey: "names")
        // var error : NSError?

        do {
            try managerObjectContext.save()
        } catch {
            print("error")
        }
        people.append(person)
    }

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return people.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
        let person = people[indexPath.row]
        // find the key of "names".
        cell.textLabel?.text = person.valueForKey("names") as? String

        // Configure the cell...

        return cell
    }


    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

Demo下载。(适应Xcode7)

Demo

提示

这个Demo在模拟机运行时可能会出现一些莫名其妙的bug,此时可以reset一下模拟器。同时,最好使用真机测试,这样不会出bug。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在iOS使用Xcode进行离线打包,需要遵循以下步骤: 1. 确保你已经安装了Xcode并拥有一个有效的开发者账号。 2. 打开Xcode并选择 "File" -> "New" -> "Project"。 3. 选择 "iOS" -> "Application" -> "Single View App",并点击 "Next"。 4. 输入项目名称和其他信息,然后点击 "Next"。 5. 选择一个位置来保存你的项目文件,然后点击 "Create"。 6. 在左侧导航栏中选择你的项目,并在 "General" 选项卡下找到 "Identity" 部分。 7. 点击 "Team" 下拉菜单并选择你的开发者账号。 8. 关闭Xcode并在终端中打开你的项目文件夹。 9. 运行以下命令来创建一个离线打包的IPA文件: ``` xcodebuild clean archive -scheme <YourSchemeName> -archivePath <YourArchivePath.xcarchive> CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO ``` 其中,`<YourSchemeName>` 是你项目中的 scheme 名称,`<YourArchivePath.xcarchive>` 是你想要保存的归档文件的路径。 10. 运行以下命令来导出IPA文件: ``` xcodebuild -exportArchive -archivePath <YourArchivePath.xcarchive> -exportOptionsPlist <YourExportOptions.plist> -exportPath <YourIPAPath.ipa> ``` 其中,`<YourArchivePath.xcarchive>` 是你刚才创建的归档文件的路径,`<YourExportOptions.plist>` 是一个导出选项的配置文件,`<YourIPAPath.ipa>` 是你想要保存的IPA文件的路径。 11. 完成后,你应该可以在 `<YourIPAPath.ipa>` 路径下找到你的IPA文件。 请注意,此方法需要你已经有一个有效的开发者账号,并且你需要使用终端来执行命令。此外,此方法可能存在不稳定性和错误,因此请谨慎使用

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值