• CoreData的基本使用


    概述:把对象存储进CoreData,大概是这个情况:
    这里写图片描述
    这里写图片描述
    那么问题来了:
    1.哪设置存储文件路径(full path)?
    2.

    1.关于UIManagedDocument
    1.1Creating a UIManagedDocument
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSURL *documentsDirectory = [[fileManager URLsForDirectory:NSDocumentDirectory
    inDomains:NSUserDomainMask] firstObject];
    NSString *documentName = @“MyDocument”;
    NSURL *url = [documentsDirectory URLByAppendingPathComponent:documentName];
    UIManagedDocument *document = [[UIManagedDocument alloc] initWithFileURL:url];
    注意:This creates the UIManagedDocument instance, but does not open nor create the underlying file(只创建了UIManagedDocument,并还没有打开或者创建了底层的文件)。

    1.2How to open or create a UIManagedDocument
    1)First, check to see if the UIManagedDocument’s underlying file exists on disk …
    BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:[url path]] ;
    … if it does, open the document using …
    [document openWithCompletionHandler:^(BOOL success) { /* block to execute when open */ }];
    … if it does not, create the document using …
    [document saveToURL:url // could (should?) use document. fileURL property here
    forSaveOperation:UIDocumentSaveForCreating
    competionHandler:^(BOOL success) { /* block to execute when create is done */ }];
    解释:用NSFileManager 去检测是否已创建了对应URL([URL path])的文件,是就打开该文件(openWithCompletionHandler:),否则创建该文件(saveToURL:forSaveOperation:completionHandler:)。具体看苹果官方文档:https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIDocument_Class/index.html#//apple_ref/occ/cl/UIDocument
    2) Example
    self.document = [[UIManagedDocument alloc] initWithFileURL: (URL *)url];
    if ([[NSFileManager defaultManager] fileExistsAtPath: [url path]]) {
    [document openWithCompletionHandler: ^(BOOL success) {
    if (success) [self documentIsReady];
    if (!success) NSLog(@“couldn’t open document at %@”, url);
    }];
    } else {
    [document saveToURL: url forSaveOperation: UIDocumentSaveForCreating
    completionHandler: ^(BOOL success) {
    if (success) [self documentIsReady];
    if (!success) NSLog(@“couldn’t create document at %@”, url);
    }];
    }
    // can’t do anything with the document yet (do it in documentIsReady)
    检查文件状态
    Once document is open/created, you can start using it
    But you might want to check the documentState when you do …
    - (void) documentIsReady
    {
    if (self.document. documentState == UIDocumentStateNormal) {
    // start using document
    }
    }

  • 相关阅读:
    服务器启动jar包详解
    linux环境安装Go环境
    crt修改默认颜色
    java调用python脚本没有返回值问题
    org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of typeavailable
    markdown个人使用总结
    windows配置免密登录linux
    idea远程debug项目
    dubbo图形化控制台
    java.lang.IllegalArgumentException: Could not resolve placeholder
  • 原文地址:https://www.cnblogs.com/iosDevZhong/p/4395227.html
Copyright © 2020-2023  润新知