分类目录归档:ALL IOS

django 安装 directadmin安装

django-admin.py startproject hello
python manage.py runserver p.smtch.com:8000

gunicorn hello.wsgi:application –bind p.smtch.com:8001


yum groupinstall -y development

yum groupinstall -y 'development tools'

curl https://raw.github.com/pypa/pip/master/contrib/get-pip.py | python
或者: wget https://raw.github.com/pypa/pip/master/contrib/get-pip.py
$ python get-pip.py

pip install virtualenv
yum install -y zlib-dev openssl-devel sqlite-devel bzip2-devel


Create and activate an environment for your application

I like to keep all my web apps in the /webapps/ directory. If you prefer /var/www/ or something else, use that instead.

$ cd /webapps/
$ virtualenv hello_django(创建一个环境)

New python executable in hello_django/bin/python
Installing distribute..............done.
Installing pip.....................done.

$ cd hello_django
$ source bin/activate
(hello_django) $ 

接着安装django

Your environment is now activated and you can proceed to install Django inside it.

(hello_django) $ pip install django

Downloading/unpacking django
(...)
Installing collected packages: django
(...)
Successfully installed django
Cleaning up...


安装完成,运行project:

django-admin.py startproject hello

接着可试运行development server:



(hello_django) $ cd hello
(hello_django) $ python manage.py runserver example.com:8000
Validating models...

0 errors found
June 09, 2013 - 06:12:00
Django version 1.5.1, using settings 'hello.settings'
Development server is running at http://example.com:8000/
Quit the server with CONTROL-C.

Application user

Even though Django has a pretty good security track record, web applications can become compromised. If the application has limited access to resources on your server, potential damage can also be limited. Your web applications should run as system users with limited privileges.

Create a user for your app, named hello and assigned to a system group called web apps

$ sudo groupadd --system webapps
$ sudo useradd --system --gid webapps --home /webapps/hello_django hello 
Gunicorn

In production we won’t be using Django’s single-threaded development server, but a dedicated application server called gunicorn.

Install gunicorn in your application’s virtual environment:
(hello_django) $ pip install gunicorn
Downloading/unpacking gunicorn
  Downloading gunicorn-0.17.4.tar.gz (372Kb): 372Kb downloaded
  Running setup.py egg_info for package gunicorn

Installing collected packages: gunicorn
  Running setup.py install for gunicorn

    Installing gunicorn_paster script to /webapps/hello_django/bin
    Installing gunicorn script to /webapps/hello_django/bin
    Installing gunicorn_django script to /webapps/hello_django/bin
Successfully installed gunicorn
Cleaning up...

安装好gunicoin,运行django程序:

(hello_django) $ gunicorn hello.wsgi:application --bind example.com:8001

http://michal.karzynski.pl/blog/2013/06/09/django-nginx-gunicorn-virtualenv-supervisor/

python manage.py runserver 27.54.250.15:8000

gunicorn hello.wsgi:application –bind 27.54.250.15:8001
Directadmin

1. 安装gcc, gcc-c++

yum install gcc
CODE

yum install gcc-c++
想当然第一次装的时候, 是一个header, 一个header,??一个RPM, 一个RPM慢慢装的啊, 哪里知道这两条命令就能全搞定. 幸好遇到这个新的公司的这个技术, 要不然还不一辈子当傻子了?

2. 之后开始安装DirectAdmin了, 其实只是按官方步骤就OK了, 我只是用中文转述一下, 哈哈.

安装之前请一定准备好DirectAdmin的授权信息, client ID, license ID, 并确定使用系统和IP都是正确的. 否则无法成功安装

1)用root帐号登录系统, 下载setup.sh文件, 运行

wget http://www.directadmin.com/setup.sh
2)改setup.sh属性,

chmod 755 setup.sh
3)运行程序

./setup.sh

Linux下python升级步骤

  首先下载源tar包

  可利用linux自带下载工具wget下载,如下所示:

1
# wget http://www.python.org/ftp/python/3.3.0/Python-3.3.0.tgz
  或自己去网上找,这里提供一个最新版的下载链接:http://xiazai.zol.com.cn/detail/33/320958.shtml

  这里我用的是第二种方法,下载的是Python-3.1.2.tar.bz2版本,下载完成后到下载目录下,解压

1
bunzip2 Python-3.1.2.tar.bz2
2
tar -xvf Python-3.1.2.tar(若是第一种方法,则直接解压缩tar -xzvf Python-3.3.0.tgz)
  进入解压缩后的文件夹

1
cd Python-3.1.2
  在编译前先在/usr/local建一个文件夹python3(作为python的安装路径,以免覆盖老的版本)

1
mkdir /usr/local/python3
  开始编译安装

1
 ./configure --prefix=/usr/local/python3
2
make
3
 make install
  此时没有覆盖老版本,再将原来/usr/bin/python链接改为别的名字

1
 mv /usr/bin/python /usr/bin/python_old
  再建立新版本python的链接

1
 ln -s /usr/local/python3/bin/python3 /usr/bin/python
  这个时候输入

1
python
  就会显示出python的新版本信息

WeB App服务端一些相关知识RestFul API

The term cloud actually has a number of meanings and discrete forms besides simple data storage.

 Software as a Service (SaaS) means applications hosted on a server that you could access and use almost as if they were installed on your local device. SaaS also to some means web application programming interfaces (APIs) that you can access remotely. Some examples of SaaS include Salesforce (www.salesforce.com), a customer relationship management (CRM) service, and GoToMeeting (www.gotomeeting.com), an online virtual meeting service.
 Infrastructure as a Service (IaaS) means the hosting of real or virtualized systems. If you need a Linux machine, for example, you can have a virtual server built
and hosted in the cloud with IaaS, removing the responsibility of building and maintaining the hardware yourself (whether that hardware is real or virtual doesn’t really matter in this model; you don’t care as the client of IaaS and in
fact may not even know). The benefit of this is that most of the responsibility for maintaining servers, worrying about updates, ensuring proper virus protection is in place, and so on, are dealt with by the provider, allowing you to focus on what really matters most to you, namely, your business. Some examples of IaaS include Amazon EC2 (http://aws.amazon.com/ec2) and Google App Engine (http://developers.google.com/appengine).
 Platform as a Service (PaaS) is effectively an extension of IaaS where instead of just a virtualized server you get a virtualized “full stack” including things such as databases, web/app servers, and programming execution environments. Examples of PaaS include IBM’s SmartCloud Application Services (www.ibm.com/cloud-computing/us/en/paas.html) and VCE’s VBLOCK (www.vce.com/products/vblock/overview).
6 CHAPTER 1: Designing My Mobile Organizer
 Network as a Service (NaaS) includes capabilities such as VPNs and “bandwidth on demand.” Once again, this removes the need to administer the hardware and/or software for your networking capabilities yourself. Any VPN, such as GigaNews’ VyprVPN (www.giganews.com/vyprvpn), is an example of NaaS.
 Storage as a Service (also abbreviated SaaS) is similar to IaaS but deals specifically with data storage. Sites such as Dropbox, Google Drive, and Microsoft’s SkyDrive are all examples of SaaS.


When you start to look at the mobile web libraries available, you’ll come across a number of options. There’s Sencha Touch (www.sencha.com), which is a very good library designed specifically for mobile web development. It allows us to develop screens using JavaScript and provides things such as widgets (grids, buttons, calendars, and so on) as well as a robust data-handling module, among lots of other things.
There’s DHTMLX Touch (www.dhtmlx.com) that provides a full HTML5-based framework and widget set for developing mobile applications.
There are also some old favorites like Dojo (www.dojotoolkit.org) and Yahoo’s YUI (www.yuilibrary.com) that, while not exclusively mobile-oriented, are capable of helping develop mobile web apps nonetheless.
However, one of the most popular general JavaScript libraries in existence (many polls indicate it is in fact the most popular) is jQuery (www.jquery.com). As a more general-purpose JavaScript library, however, jQuery isn’t focused on mobile development. Although not an all-inclusive description,probably the main goal of jQuery is to make Document Object Model (DOM) manipulation easier, and it does this exceedingly well. It’s extremely fast, lightweight, and, most importantly for the purposes of this discussion, extensible.
That extensibility comes into play with jQuery Mobile (www.jquerymobile.com), which is built on top of jQuery. This library is an HTML5-based system for developing mobile UIs. It contains widgets and helper functions for putting such apps together, among other things

Server-Side Architecture

With the client-side decisions of mobile web app using jQuery Mobile decided, how do we build the server side? Clearly, there’s a ton of choices there too.
Do you already know Java (www.oracle.com)? Then that might be a good choice. What about PHP (http://us.php.net)? Again, there’s nothing wrong with PHP in my mind, even though some would argue that it isn’t appropriate for “professional” development. I’m not here to pass judgment, though! If you know PHP already, then it’s certainly worth considering. Are Microsoft technologies (www.microsoft.com) up your alley? If that’s a skill set you already have, then they are not a bad choice. Ruby on Rails (www.rubyonrails.org) perhaps? Yes, it’s worthy of consideration certainly, as are any of a dozen other possible technologies you might come across.
All of these also require potentially significant server infrastructures. Java requires an entire servlet container. PHP is an extension to an existing web server. Microsoft of course requires IIS, its proprietary web server, plus the appropriate extensions. Ruby on Rails is its own server product essentially. All of these also require administration expertise and are therefore somewhat complex to work with, depending on what you might already know.
At the end of the day, there’s another option that’s fast becoming very popular, and for good reason: node.js (www.nodejs.org). One of the key benefits to node.js is that the code you write on the server side is written in JavaScript, just as your client-side code is. Since one of the reasons I stated for going with a mobile web approach is reuse of skills, shouldn’t that apply to the server side as well?
I think so! The idea of the same language on both sides of the conversation, meaning client side and server side, and assuming performance isn’t a problem, is attractive to many people.
The other big benefit of node.js is that it is designed for high performance and concurrency from the start. While neither of these concerns is particularly big for My Mobile Organizer frankly, there’s no good reason to use technologies that hamstring us in either regard.

What About the Database?

Of course, just deciding on node.js for the server side isn’t quite the whole story. There’s also data storage to consider. We need a database of some sort too, don’t we?
Of course we do!
26 CHAPTER 1: Designing My Mobile Organizer
So then, which do we use? Oracle (www.oracle.com)? It’s a great database supporting tons of massive, high-availability systems out there. Yet, it’s expensive, so it’s probably not the best choice for our relatively minor app. What about the popular MySQL (www.mysql.com)? It’s very good, no question; I use it tons myself. To make a long story short, there are many choices to choose from in this area, too many to name.
Given that we’ve decided on node.js, are there any options that work well with it? Yes, all of the above in fact can be used with it. There’s another choice, though, that is very popular and is part of the “NoSQL” movement: MongoDB.
The NoSQL movement is an approach to data storage that eschews the need for Structured Query Language (SQL) that all relational database management systems (RDBMSs) are based upon. It’s fundamentally different in that you store “documents,” as opposed to relational data in the form
of tables and rows of data. It goes along fantastically well with JavaScript, and therefore node.js, because a “document” can be simply an object represented with JSON, which of course is native, even the lingua franca really, of JavaScript. MongoDB is one very popular implementation of this concept, and it integrates exceedingly well with node.js.
Chapter 6 is where we’ll deep-dive into MongoDB so for now, suffice to say that its NoSQL approach, and the simple API made available to our node.js app for it, makes it easy to work with and provides a good data storage mechanism for our PIM app.

his stack, the combination of PhoneGap, jQuery, jQuery Mobile, node.js, REST, and MongoDB, is rapidly becoming a popular one because it is flexible, is easy to learn, performs well (if you do your job as a developer reasonably well at least), and is based on open, free technologies.

All About Core Data–NSManagedObjectContextDidSaveNotification

Core Data sits between your application and a persistent store, which is the generic term given to a data file such as an SQLite database, XML file (which can’t be used as a persistent store on iOS), or Binary (atomic) store. These files are called “persistent” because they can survive the underlying hardware being reset.

A persistent store coordinator can have multiple persistent stores

a managed object model is shown sitting between a persistent store coordinator and a managed object context.

The NSMainQueueConcurrencyType should be used when you want the context to operate on the main thread. Any heavy work performed in this queue may slow down or even freeze the user interface. You need at least one context working in the foreground to update user interface elements.
■ The NSPrivateQueueConcurrencyType should be used when you don’t want the context to operate on the main thread. This is an ideal concurrency type for potentially heavy work, such as saving or importing data.
■ The NSConfinementConcurrencyType is the default legacy option, which you should typically avoid unless you need backward compatibility with pre–iOS 5.0 devices.


The sqlite file is the database file, as per usual.
■ The sqlite-wal file is the Write-Ahead Log file containing uncommitted database transactions. If you delete this file, you will lose data. If this file does not exist, there are no pending transactions waiting to be committed.
■ The sqlite-shm file is the Shared Memory file containing an index of the WAL file. This file can be regenerated automatically so you don’t need to worry about it.


A deep copy involves copying managed objects and their relationships from one persistent store to another.

How would you watch a document’s managedObjectContext?!
 - (void)viewDidAppear:(BOOL)animated
 {
     [super viewDidAppear:animated];
     [center addObserver:self
                selector:@selector(contextChanged:)
                    name:NSManagedObjectContextDidSaveNotification
object:document.managedObjectContext]; //don’tpassnilhere!
 }
 - (void)viewWillDisappear:(BOOL)animated
 {
     [center removeObserver:self
                       name:NSManagedObjectContextDidSaveNotification
                     object:document.managedObjectContext];
     [super viewWillDisappear:animated];
 }
NSManagedObjectContextDidSaveNotification !
  - (void)contextChanged:(NSNotification *)notification
  {
// The notification.userInfo object is an NSDictionary with the following keys: NSInsertedObjectsKey // an array of objects which were inserted NSUpdatedObjectsKey // an array of objects whose attributes changed NSDeletedObjectsKey // an array of objects which were deleted
}!
Merging changes!
If you get notified that another NSManagedObjectContext has changed your database ...! ... you can just refetch (if you haven’t changed anything in your NSMOC, for example).!
... or you can use the NSManagedObjectContext method:!
- (void)mergeChangesFromContextDidSaveNotification:(NSNotification *)notification;

[_myAppDelegate.managedObjectContext mergeChangesFromContextDidSaveNotification:notification];

Deletion

Deleting objects from the database is easy (sometimes too easy!)! [aDocument.managedObjectContext deleteObject:photo]; !
Make sure that the rest of your objects in the database are in a sensible state after this.! Relationships will be updated for you (if you set Delete Rule for relationship attributes properly).! And don’t keep any strong pointers to photo after you delete it!!
prepareForDeletion !
This is another method we sometimes put in a category of an NSManagedObject subclass ...!
  @implementation Photo (Deletion)
  - (void)prepareForDeletion
  {
// we don’t need to set our whoTook to nil or anything here (that will happen automatically)!
// but if Photographer had, for example, a “number of photos taken” attribute,!
// we might adjust it down by one here (e.g. self.whoTook.photoCount--). }
@end

Querying

Creating an NSFetchRequest!
We’ll consider each of these lines of code one by one ...
 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@“Photo”];
 request.fetchBatchSize = 20;
 request.fetchLimit = 100;
 request.sortDescriptors = @[sortDescriptor];
 request.predicate = ...;
Specifying the kind of Entity we want to fetch! A given fetch returns objects all of the same Entity.!
You can’t have a fetch that returns some Photos and some Photographers (it’s one or the other).! Setting fetch sizes/limits!
If you created a fetch that would match 1000 objects, the request above faults 20 at a time. And it would stop fetching after it had fetched 100 of the 1000

NSPredicate !

This is the guts of how we specify exactly which objects we want from the database.!
Predicate formats!
Creating one looks a lot like creating an NSString, but the contents have semantic meaning.
  NSString *serverName = @“flickr-5”;
  NSPredicate *predicate =
      [NSPredicate predicateWithFormat:@“thumbnailURL contains %@”, serverName];
Examples!
@“uniqueId = %@”, [flickrInfo objectForKey:@“id”] // unique a photo in the database @“name contains[c] %@”, (NSString *) // matches name case insensitively!
@“viewed > %@”, (NSDate *) // viewed is a Date attribute in the data mapping! @“whoTook.name = %@”, (NSString *) // Photo search (by photographer’s name)!
@“any photos.title contains %@”, (NSString *) // Photographer search (not a Photo search)! Many more options. Look at the class documentation for NSPredicate.

NSCompoundPredicate

NSCompoundPredicate !
You can use AND and OR inside a predicate string, e.g. @“(name = %@) OR (title = %@)”! Or you can combine NSPredicate objects with special NSCompoundPredicates.
NSArray *array = @[predicate1, predicate2];
NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:array]; This predicate is “predicate1 AND predicate2”. Or available too, of course

Advanding Querying

Key Value Coding!
Can actually do predicates like @“photos.@count > 5” (Photographers with more than 5 photos).! @count is a function (there are others) executed in the database itself.! https://developer.apple.com/library/ios/documentation/cocoa/conceptual/KeyValueCoding/Articles/CollectionOperators.html.!
By the way, all this stuff (and more) works on dictionaries, arrays and sets too ...!
e.g. [propertyListResults valueForKeyPath:@“photos.photo.@avg.latitude”] on Flickr results!
returns the average latitude of all of the photos in the results (yes, really)!
e.g. @“photos.photo.title.length" would return an array of the lengths of the titles of the photos!

Example!

Let’s say we want to query for all Photographers ...!
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@“Photographer”];
... who have taken a photo in the last 24 hours ...!
NSDate *yesterday = [NSDate dateWithTimeIntervalSinceNow:-24*60*60]; !
request.predicate = [NSPredicate predicateWithFormat:@“any photos.uploadDate > %@”, yesterday]; ! ... sorted by the Photographer’s name ...
request.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@“name” ascending:YES]];

How do you create an NSFetchedResultsController?

Just need the NSFetchRequest to drive it (and a NSManagedObjectContext to fetch from).
Let's say we want to show all photos taken by someone with the name photogName in our table:
 NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@“Photo”];
 request.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@“title” ...]];
 request.predicate = [NSPredicate predicateWithFormat:@“whoTook.name = %@”, photogName];
 NSFetchedResultsController *frc = [[NSFetchedResultsController alloc]
     initWithFetchRequest:(NSFetchRequest *)request
     managedObjectContext:(NSManagedObjectContext *)context
       sectionNameKeyPath:(NSString *)keyThatSaysWhichSectionEachManagedObjectIsIn
                cacheName:@“MyPhotoCache”];  // careful!
Be sure that any cacheName you use is always associated with exactly the same request. It’s okay to specify nil for the cacheName (no cacheing of fetch results in that case).
It is critical that the sortDescriptor matches up with the keyThatSaysWhichSection...
The results must sort such that all objects in the first section come first, second second, etc

NSFetchedResultController–CoreDataTableViewController

//
//  CoreDataTableViewController.h
//
//  Created for Stanford CS193p Fall 2013.
//  Copyright 2013 Stanford University. All rights reserved.
//
// This class mostly just copies the code from NSFetchedResultsController's documentation page
//   into a subclass of UITableViewController.
//
// Just subclass this and set the fetchedResultsController.
// The only UITableViewDataSource method you'll HAVE to implement is tableView:cellForRowAtIndexPath:.
// And you can use the NSFetchedResultsController method objectAtIndexPath: to do it.
//
// Remember that once you create an NSFetchedResultsController, you CANNOT modify its @propertys.
// If you want new fetch parameters (predicate, sorting, etc.),
//  create a NEW NSFetchedResultsController and set this class's fetchedResultsController @property again.
//

#import 
#import 

@interface CoreDataTableViewController : UITableViewController 

// The controller (this class fetches nothing if this is not set).
@property (strong, nonatomic) NSFetchedResultsController *fetchedResultsController;

// Causes the fetchedResultsController to refetch the data.
// You almost certainly never need to call this.
// The NSFetchedResultsController class observes the context
//  (so if the objects in the context change, you do not need to call performFetch
//   since the NSFetchedResultsController will notice and update the table automatically).
// This will also automatically be called if you change the fetchedResultsController @property.
- (void)performFetch;

// Set to YES to get some debugging output in the console.
@property BOOL debug;

@end

//
//  CoreDataTableViewController.m
//
//  Created for Stanford CS193p Fall 2013.
//  Copyright 2013 Stanford University. All rights reserved.
//

#import "CoreDataTableViewController.h"

@implementation CoreDataTableViewController

#pragma mark - Fetching

- (void)performFetch
{
    if (self.fetchedResultsController) {
        if (self.fetchedResultsController.fetchRequest.predicate) {
            if (self.debug) NSLog(@"[%@ %@] fetching %@ with predicate: %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), self.fetchedResultsController.fetchRequest.entityName, self.fetchedResultsController.fetchRequest.predicate);
        } else {
            if (self.debug) NSLog(@"[%@ %@] fetching all %@ (i.e., no predicate)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), self.fetchedResultsController.fetchRequest.entityName);
        }
        NSError *error;
        BOOL success = [self.fetchedResultsController performFetch:&error];
        if (!success) NSLog(@"[%@ %@] performFetch: failed", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
        if (error) NSLog(@"[%@ %@] %@ (%@)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), [error localizedDescription], [error localizedFailureReason]);
    } else {
        if (self.debug) NSLog(@"[%@ %@] no NSFetchedResultsController (yet?)", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
    }
    [self.tableView reloadData];
}

- (void)setFetchedResultsController:(NSFetchedResultsController *)newfrc
{
    NSFetchedResultsController *oldfrc = _fetchedResultsController;
    if (newfrc != oldfrc) {
        _fetchedResultsController = newfrc;
        newfrc.delegate = self;
        if ((!self.title || [self.title isEqualToString:oldfrc.fetchRequest.entity.name]) && (!self.navigationController || !self.navigationItem.title)) {
            self.title = newfrc.fetchRequest.entity.name;
        }
        if (newfrc) {
            if (self.debug) NSLog(@"[%@ %@] %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), oldfrc ? @"updated" : @"set");
            [self performFetch];
        } else {
            if (self.debug) NSLog(@"[%@ %@] reset to nil", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
            [self.tableView reloadData];
        }
    }
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    NSInteger sections = [[self.fetchedResultsController sections] count];
    return sections;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSInteger rows = 0;
    if ([[self.fetchedResultsController sections] count] > 0) {
        id  sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
        rows = [sectionInfo numberOfObjects];
    }
    return rows;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
	return [[[self.fetchedResultsController sections] objectAtIndex:section] name];
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
	return [self.fetchedResultsController sectionForSectionIndexTitle:title atIndex:index];
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    return [self.fetchedResultsController sectionIndexTitles];
}

#pragma mark - NSFetchedResultsControllerDelegate

- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
{
    [self.tableView beginUpdates];
}

- (void)controller:(NSFetchedResultsController *)controller
  didChangeSection:(id )sectionInfo
		   atIndex:(NSUInteger)sectionIndex
	 forChangeType:(NSFetchedResultsChangeType)type
{
    switch(type)
    {
        case NSFetchedResultsChangeInsert:
            [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
            break;
            
        case NSFetchedResultsChangeDelete:
            [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
            break;
    }
}


- (void)controller:(NSFetchedResultsController *)controller
   didChangeObject:(id)anObject
	   atIndexPath:(NSIndexPath *)indexPath
	 forChangeType:(NSFetchedResultsChangeType)type
	  newIndexPath:(NSIndexPath *)newIndexPath
{		
    switch(type)
    {
        case NSFetchedResultsChangeInsert:
            [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;
            
        case NSFetchedResultsChangeDelete:
            [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;
            
        case NSFetchedResultsChangeUpdate:
            [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;
            
        case NSFetchedResultsChangeMove:
            [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
            [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
            break;
    }
}

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
    [self.tableView endUpdates];
}

@end


iCloud

icloud

  • The Application Stores Directory, also known as the application sandbox, is a
    local directory that currently holds the original Grocery-Dude.sqlite store. An iCloud.sqlite store will be added to this folder in a subfolder specific to each iCloud user. The per-user subfolders are managed transparently by Core Data. The folder structure is shown at the end of the chapter in the “Exercises” section.
  • The Ubiquity Container is where iCloud documents and data specific to the authenticated iCloud user are found. Everything in this folder is synchronized automatically with the iCloud servers. If a directory with a .nosync suffix is stored
    in the ubiquity container, its contents will not be synchronized. You may have seen implementations of iCloud where the iCloud Store was placed in a .nosync folder of the ubiquity container. This approach is no longer recommended since iOS 7 because it prevents Core Data from transparently managing a Fallback Store. A Fallback Store is used to provide seamless transitions between iCloud accounts and reduce the time it takes for the iCloud Store to become usable for the first time. The Fallback Store is also used when the user is logged out of iCloud, or has disabled iCloud Documents & Data.
  • iCloud is the name of the service allowing a user’s data to be synchronized across all
    of his or her devices. It is possible to see the contents of your iCloud container for debugging purposes at https://developer.icloud.com. You can also perform metadata queries to inspect the contents of iCloud or use the iCloud Debug Navigator introduced in Xcode 5, which will be shown later in the chapter. Each application using iCloud has its own directory at the root of iCloud, and applications from the same developer can be configured to share a ubiquity container within it. This is useful if you need to maintain separate free and paid versions of an application that need to access the same data.

Create file to iCloud
Icloud’s local path from phone: file:///private/var/mobile/Library/Mobile%20Documents/TeamID~com~toogoogoo~iCloud/

iCloud’s local path from simulator: file:///Users/xushao/Library/Application%20Support/iPhone%20Simulator/7.0.3/Library/Mobile%20Documents/TeamID ~com~toogoogoo~Test/

如果在该目录手动创建文件,icloud也会同步创建

NSURL * iCloudURL = [self.fManager URLForUbiquityContainerIdentifier:nil];这个url的目录为:根目录

//
//  iCloudAppDelegate.m
//  iCloud
//
//  Created by xushao on 2/24/14.
//  Copyright (c) 2014 TGG. All rights reserved.
//

#import "iCloudAppDelegate.h"

@interface iCloudAppDelegate ()
@property(nonatomic, strong)NSFileManager *fManager;
@property(nonatomic, strong)NSMetadataQuery *iCloudQuery;

@end

@implementation iCloudAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    /*
    NSString *stringValuekey2 = @"My String";
    NSString *stringValueKey = @"MyStringKey";
    NSUbiquitousKeyValueStore *KVStore =  [[NSUbiquitousKeyValueStore alloc] init];
    
    if ([[KVStore stringForKey:stringValuekey2] length]==0) {
        [self alert:@"no string, settting"];
        [KVStore setString:@"this is string" forKey:stringValueKey];
        [KVStore setString:@"stringValuekey2" forKey:stringValuekey2];
    }else{
        [self alert:[NSString stringWithFormat:@"Result is :%@ and %@",[KVStore stringForKey:stringValueKey],[KVStore stringForKey:stringValuekey2]]];
    }
    
    
    
    
    if (![fManager fileExistsAtPath:[[self documentURL] path]]) {
        
        [self alert:[NSString stringWithFormat:@"createDirectoryAtPath %@ ", [self documentURL]]];
        [fManager createDirectoryAtPath:[[self documentURL] path] withIntermediateDirectories:YES attributes:nil error:nil];
    }else{
        [self alert:@"File already exit"];
    }
     

    if (![self.fManager fileExistsAtPath:[[self documentURL] path]]) {
        
        [self alert:[NSString stringWithFormat:@"createDirectoryAtURL %@ ", [self documentURL]]];
        
        [self.fManager createDirectoryAtURL:[self documentURL] withIntermediateDirectories:YES
                                 attributes:nil error:nil  ];
        //[self.fManager createDirectoryAtPath:[[self documentURL] path] withIntermediateDirectories:YES attributes:nil error:nil];
    }else{
        [self alert:@"File already exit"];
    }
     */
    self.fManager = [NSFileManager defaultManager];
   NSString * TeamID = @"FUHS6YZAHW";
    NSString *buddleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
    NSString *identifier = [NSString stringWithFormat:@"%@.%@", TeamID, buddleIdentifier];
    
    
   NSURL * iCloudURL = [self.fManager URLForUbiquityContainerIdentifier:nil];
    NSError *error = nil;
   // NSString *documentDirec = [[iCloudURL path] stringByAppendingPathComponent:@"Documents"];
    NSURL *documentURL = [iCloudURL URLByAppendingPathComponent:@"Documents" isDirectory:YES];
    //NSString *createDocument = [documentDirec stringByAppendingPathComponent:@"David"];
    if (![self.fManager fileExistsAtPath:[documentURL path]]) {
        
        
        [self.fManager createDirectoryAtPath:[documentURL path] withIntermediateDirectories:YES attributes:nil error:&error];
        if (!error) {
            [self alert:[NSString stringWithFormat:@"create iCloudURL: %@ ", iCloudURL]];
            NSLog(@"%@",iCloudURL);
        }else{
            NSLog(@"error1");
        }
        
    }else{
        
        NSString *textString = @"This is text";
        NSURL *FileURL = [documentURL URLByAppendingPathComponent:@"latest.text"];
       // NSString *path = [documentURL stringByAppendingPathComponent:@"JacobString.sql"];
        NSError *error = nil;
        if ([textString writeToURL:FileURL atomically:YES encoding:NSUTF8StringEncoding error:&error]) {
            if (!error) {
                //NSData *data = [self.fManager contentsAtPath:path];
                //NSString *string = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
                //[self alert:[NSString stringWithFormat:@"The content is : %@", string]];
            }else{
                 NSLog(@"error2");
            }
        }else{
            [self alert:@"Couldn't write to"];
        }
    }
    
    
    //
    NSURL *fileURL = [[self documentURL] URLByAppendingPathComponent:@"JacobLocal.String.txt"];
    if ([self.fManager fileExistsAtPath:[fileURL path]]) {
        if ([self.fManager setUbiquitous:YES itemAtURL:fileURL destinationURL:documentURL error:&error]) {
            if (!error) {
                NSLog(@"successful upload");
            }else{
                NSLog(@"error3");
            }
        }else{
            NSLog(@"couldn't");
        }
        
    }
    
    if ([self.iCloudQuery startQuery]) {
        [self alert:@"start query"];
    }else{
        NSLog(@"not query");
    }
    
    
    return YES;
    
}

-(NSMetadataQuery *)iCloudQuery
{
    if (!_iCloudQuery) {
        _iCloudQuery = [[NSMetadataQuery alloc] init];
        _iCloudQuery.searchScopes = [NSArray arrayWithObject:NSMetadataQueryUbiquitousDocumentsScope];
        _iCloudQuery.predicate = [NSPredicate predicateWithFormat:@"%K LIKE '*'",NSMetadataItemFSNameKey];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(preocessQueryResult:) name:NSMetadataQueryDidFinishGatheringNotification object:_iCloudQuery];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(preocessQueryResult:) name:NSMetadataQueryDidUpdateNotification object:_iCloudQuery];
    
    }
    
    return _iCloudQuery;
}

-(void)preocessQueryResult:(NSNotification *)notification{
    [self.iCloudQuery disableUpdates];
    NSMutableArray *UrlArray = [[NSMutableArray alloc] init];
    NSUInteger resultIndex = [self.iCloudQuery resultCount];
    NSLog(@"resultIndex is %d",resultIndex);

    for (int i = 0; i < resultIndex; i++) {
        NSMetadataItem *item = [self.iCloudQuery resultAtIndex:i];
        NSURL *url = [item valueForAttribute:NSMetadataItemURLKey];

        [UrlArray addObject:[url pathComponents]];
    }
    
    [self.iCloudQuery enableUpdates];
}

-(NSURL *)documentURL{
    NSURL *documentDirectory = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    return [documentDirectory URLByAppendingPathComponent:@"TGGDocument"];
}

-(void)alert:(NSString *)msg{
    
    [[[UIAlertView alloc] initWithTitle:@"Noticed" message:msg delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] show];
}
	

DocumentTVC

//
// DocumentTVC.m
// Test
//
// Created by xushao on 2/23/14.
// Copyright (c) 2014 TGG. All rights reserved.
//

#import "DocumentTVC.h"

@interface DocumentTVC ()
@property(nonatomic, strong)NSArray *documents;
@property(nonatomic, strong)NSMetadataQuery *icloudQuery;
@end

@implementation DocumentTVC

-(void)viewDidLoad
{
if (DEBUG == 1) {
NSLog(@"%@ is %@",self.class, NSStringFromSelector(_cmd));
}
[super viewDidLoad];
NSLog(@"%@", [self iCloudURL]);
}
-(NSURL *)iCloudURL{
return [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
}

@synthesize documents = _documents;

-(void)setDocuments:(NSArray *)documents
{
_documents = documents;
[self.tableView reloadData];
}

-(void)processIcloudqueryResult:(NSNotification *)notificatin{
[self.icloudQuery disableUpdates];

NSUInteger resultCount = [self.icloudQuery resultCount];

for (int i = 0; i < resultCount; i ++) { NSMetadataItem *item = [self.icloudQuery resultAtIndex:i]; NSURL *url = [item valueForAttribute:NSMetadataItemURLKey]; } } /* [item valueForAttribute:NSMetadataItemURLKey]; NSString * const NSMetadataItemFSNameKey; NSString * const NSMetadataItemDisplayNameKey; NSString * const NSMetadataItemURLKey; NSString * const NSMetadataItemPathKey; NSString * const NSMetadataItemFSSizeKey; NSString * const NSMetadataItemFSCreationDateKey; NSString * const NSMetadataItemFSContentChangeDateKey; */ -(NSMetadataQuery *)icloudQuery { if (!_icloudQuery) { _icloudQuery = [[NSMetadataQuery alloc] init]; _icloudQuery.searchScopes = [NSArray arrayWithObject:NSMetadataQueryUbiquitousDocumentsScope]; //NSString * const NSMetadataQueryUbiquitousDocumentsScope; // NSString * const NSMetadataQueryUbiquitousDataScope; _icloudQuery.predicate = [NSPredicate predicateWithFormat:@"%K like '*'",NSMetadataItemFSNameKey ]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(processIcloudqueryResult:) name:NSMetadataQueryDidFinishGatheringNotification object:_icloudQuery]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(processIcloudqueryResult:) name:NSMetadataQueryDidUpdateNotification object:_icloudQuery]; } return _icloudQuery; } -(void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; if (![self.icloudQuery isStarted]) { [self.icloudQuery enableUpdates]; } } -(void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; [self.icloudQuery disableUpdates]; } #pragma mark - Table view data source - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // Return the number of rows in the section. return [self.documents count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Document Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; // Configure the cell... cell.textLabel.text = [[self.documents objectAtIndex:indexPath.row] lastPathComponent]; return cell; } /* // Override to support conditional editing of the table view. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { // Return NO if you do not want the specified item to be editable. return YES; } */ /* // Override to support editing the table view. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { // Delete the row from the data source [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade]; } else if (editingStyle == UITableViewCellEditingStyleInsert) { // 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. - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath { } */ /* // Override to support conditional rearranging of the table view. - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath { // Return NO if you do not want the item to be re-orderable. return YES; } */ /* #pragma mark - Navigation // In a story board-based application, you will often want to do a little preparation before navigation - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ @end

enumerateObjectsUsingBlock详解

NSArray *anArray=[NSArray arrayWithObjects:@"This", @"is", @"a", @"test", nil]; 
NSString *string=@"test";
[anArray enumerateObjectsUsingBlock:^(id obj, NSUInteger index, BOOL *stop)
{
  if([obj localizedCaseInsensitiveCompare:string] == NSOrderedSame)
  {
    // 对返回的obj做点别的事情
  *stop=YES;

  }

要是anArray对象中有个单词是@”test”,那么就把指针*stop设置为YES,以通知anArray对象提前停止枚举。块除了id obj和BOOL *stop参数,还有一个NSUInteger index参数。index参数让块中的算法知道当前元素的位置,这对这样的并发枚举非常有用。要是没有这个参数,访问索引的唯一方式就是使用indexOfObject:方法,这样影响效率

CoreData: Relationship 中的Delete Rules

下面是详细说明,简单点说,假如有一个relationship: Photo and Photographer如下图:

relateionship

 

当photos设置:nullify 时, 删除一个photographer, 则对应的photos 会设置他的所有者为nil;

Cascade则会删除对应的所有photos;

The Nullify delete rule is a good default for most situations. When an object is deleted and this rule is in place, related objects nil out their relationship to the deleted object. For example, assume a unit object named Kg is related to some item objects. If a Nullify delete rule was set on the items relationship and the Kg unit object was deleted, the related item objects would set their unit property to nil.

■ The Cascade delete rule propagates deletions through the relationship. For example, assume a unit object named Kg is related to some item objects. If a Cascade delete rule was set on the items relationship and the Kg unit object was deleted, all the related item objects would be deleted, too.

■ The Deny delete rule prevents the deletion of an object if it still has related objects. For example, assume a unit object named Kg is related to some item objects. If a Deny delete rule was set on the items relationship and the Kg unit object was deleted, the existence of related item objects would cause a validation error when the context was saved. When you use a Deny delete rule, you need to ensure that there are no related objects at the relationship destination before deleting the source object.

■ The No Action delete rule is a strange one that will actually leave your object graph in an inconsistent state. If you use this delete rule, it is up to you to manually set the inverse relationship to something valid. Only corner-case situations call for this delete rule.

用代码创建一个CoreData

下图描绘了被管理对象上下文(Managed Object Context)包含2个被管理对象(Managed Object),对应着数据库中2条记录。其中一个对象的属性值已经在内存中更新过了,但还没有提交到数据库保存。另外,还有2条记录在数据库中,并没有对应的被管理对象(Managed Object)。
Managed-Object-Context

一个实体描述对象(Entity Description Object)描述了数据库中一个数据表实体,包括表名称、表对应的被管理对象的名称、属性(Attributes)和关系(Relationships)等等。

下图描绘了实体描述对象、数据库中数据表和被管理对象(对应数据库表的一条记录)之间的关系。
Managed-Object-Model

从上图可以看出,每一个被管理对象(Managed Object)都有对应实体对象的引用。
Core Data使用模型(Model)来映射应用程序中被管理对象和数据库中的数据记录。需要注意的是,如果我们修改数据库的Schema,Core Data将无法使用之前创建的模型来读取数据库记录了。很多持久化机制都存在这个问题。

advanced_persistent_stack

NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory
inDomains:NSUserDomainMask] lastObject];
NSURL *storeDatabaseURL = [url URLByAppendingPathComponent:@"ShoppingCart Database"];
// url is now /ShoppingCart Database
NSError *error = nil;
NSPersistentStoreCoordinator *persistentStoreCoordinator =
[[NSPersistentStoreCoordinator alloc]
initWithManagedObjectModel:[NSManagedObjectModel mergedModelFromBundles:nil]];
if(![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:storeDatabaseURL options:nil error:&error])
{
NSLog(@"Error while loading persistent store ...%@", error);
}

_managedObjectContext = [[NSManagedObjectContext alloc] init];
[_managedObjectContext setPersistentStoreCoordinator:persistentStoreCoordinator];

相关文章: core data创建shopping app

#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>

@interface CoreDataHelper :NSObject

@property (nonatomic, readonly) NSManagedObjectContext       *context;
@property (nonatomic, readonly) NSManagedObjectModel         *model;
@property (nonatomic, readonly) NSPersistentStoreCoordinator *coordinator;
@property (nonatomic, readonly) NSPersistentStore            *store;

- (void)setupCoreData;
- (void)saveContext;
@end

CoreDataHelper.m

#import "CoreDataHelper.h"

@implementation CoreDataHelper
#define debug 1

#pragma mark - FILES
NSString *storeFilename = @"Grocery-Dude.sqlite";

#pragma mark - PATHS
- (NSString *)applicationDocumentsDirectory {
    if (debug==1) {
        NSLog(@"Running %@ '%@'", self.class,NSStringFromSelector(_cmd));
    }
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES) lastObject];
}
- (NSURL *)applicationStoresDirectory {
    if (debug==1) {
        NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
    }

    NSURL *storesDirectory =
    [[NSURL fileURLWithPath:[self applicationDocumentsDirectory]]
     URLByAppendingPathComponent:@"Stores"];

    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:[storesDirectory path]]) {
        NSError *error = nil;
        if ([fileManager createDirectoryAtURL:storesDirectory
                  withIntermediateDirectories:YES
                                   attributes:nil
                                        error:&error]) {
            if (debug==1) {
                NSLog(@"Successfully created Stores directory");}
        }
        else {NSLog(@"FAILED to create Stores directory: %@", error);}
    }
    return storesDirectory;
}
- (NSURL *)storeURL {
    if (debug==1) {
        NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
    }
    return [[self applicationStoresDirectory]
            URLByAppendingPathComponent:storeFilename];
}

#pragma mark - SETUP
- (id)init {
    if (debug==1) {
        NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
    }
    self = [super init];
    if (!self) {return nil;}

    _model = [NSManagedObjectModel mergedModelFromBundles:nil];
    _coordinator = [[NSPersistentStoreCoordinator alloc]
                    initWithManagedObjectModel:_model];
    _context = [[NSManagedObjectContext alloc]
                initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_context setPersistentStoreCoordinator:_coordinator];
    return self;
}
- (void)loadStore {
    if (debug==1) {
        NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
    }
    if (_store) {return;} // Don’t load store if it's already loaded

    NSDictionary *options =
  @{
    NSMigratePersistentStoresAutomaticallyOption:@YES ,NSInferMappingModelAutomaticallyOption:@NO ,NSSQLitePragmasOption: @{@"journal_mode": @"DELETE"}
    };

    NSError *error = nil;
    _store = [_coordinator addPersistentStoreWithType:NSSQLiteStoreType
                                        configuration:nil
                                                  URL:[self storeURL]
                                              options:options error:&error];
    if (!_store) {NSLog(@"Failed to add store. Error: %@", error);abort();}
    else         {if (debug==1) {NSLog(@"Successfully added store: %@", _store);}}
}
- (void)setupCoreData {
    if (debug==1) {
        NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
    }
    [self loadStore];
}

#pragma mark - SAVING
- (void)saveContext {
    if (debug==1) {
        NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
    }
    if ([_context hasChanges]) {
        NSError *error = nil;
        if ([_context save:&error]) {
            NSLog(@"_context SAVED changes to persistent store");
        } else {
            NSLog(@"Failed to save _context: %@", error);
        }
    } else {
        NSLog(@"SKIPPED _context save, there are no changes!");
    }
}

@end

#import "AppDelegate.h"
#import "Item.h"
#import "Amount.h"

@implementation AppDelegate
#define debug 1

- (void)demo {
    if (debug==1) {
        NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
    }
    /*
    NSArray *newItemNames = [NSArray arrayWithObjects:
                             @"Apples", @"Milk", @"Bread", @"Cheese", @"Sausages", @"Butter", @"Orange Juice", @"Cereal", @"Coffee", @"Eggs", @"Tomatoes", @"Fish", nil];
    for (NSString *newItemName in newItemNames) { Item *newItem =
        [NSEntityDescription insertNewObjectForEntityForName:@"Item" inManagedObjectContext:_coreDataHelper.context];
        newItem.name = newItemName;
        NSLog(@"Inserted New Managed Object for '%@'", newItem.name); }

     for (int i = 1; i < 5000; i++) {      Meansure *newMeasurement =      [NSEntityDescription insertNewObjectForEntityForName:@"Meansure"      inManagedObjectContext:_coreDataHelper.context];      newMeasurement.abc =      [NSString stringWithFormat:@"-->> LOTS OF TEST DATA x%i",i]; NSLog(@"Inserted %@",newMeasurement.abc);
     }
     [_coreDataHelper saveContext];
   */

    NSFetchRequest *request =
    [NSFetchRequest fetchRequestWithEntityName:@"Amount"]; [request setFetchLimit:50];
    NSError *error = nil;
    NSArray *fetchedObjects =
    [_coreDataHelper.context executeFetchRequest:request error:&error];
    if (error) {NSLog(@"%@", error);} else {
        for (Amount *measurement in fetchedObjects) { NSLog(@"Fetched Object = %@", measurement.xyz);
        } }

}

- (CoreDataHelper*)cdh {
    if (debug==1) {
        NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
    }
    if (!_coreDataHelper) {
        _coreDataHelper = [CoreDataHelper new];
        [_coreDataHelper setupCoreData];
    }
    return _coreDataHelper;

}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    if (debug==1) {
        NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
    }
    // Override point for customization after application launch.
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    if (debug==1) {
        NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
    }
    // 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.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    if (debug==1) {
        NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
    }
    // 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.
    [[self cdh] saveContext];
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    if (debug==1) {
        NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
    }
    // 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.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    if (debug==1) {
        NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
    }
    // 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.

    [self cdh];
    [self demo];
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    if (debug==1) {
        NSLog(@"Running %@ '%@'", self.class, NSStringFromSelector(_cmd));
    }
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    [[self cdh] saveContext];
}

@end

IOS7-CoreDAta系列 fetch Request Template ForName

To use a fetch request template, you’ll need to send a message to the managed object model, telling it the name of the template to use.

NSFetchRequest *request =
[[[_coreDataHelper model] fetchRequestTemplateForName:@"Test"] copy];
NSSortDescriptor *sort =
[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES]; [request setSortDescriptors:[NSArray arrayWithObject:sort]];
NSArray *fetchedObjects =
[_coreDataHelper.context executeFetchRequest:request error:nil];
Fetching Managed Objects 41

42
Chapter 2 Managed Object Model Basics
for (Item *item in fetchedObjects) { NSLog(@"Fetched Object = %@", item.name);
}

IOS7-CoreDAta系列:Attribute相关设置

Transient properties are never written to the persistent store. Although it may seem odd to have a property that is never persisted, there are scenarios where you need a property only in the managed object context. For example, you may wish to calculate a value on the fly and then store the result in a transient property. Being in a context allows those properties to benefit from features such as undo and redo.

Optional properties aren’t required to have a value. All properties are originally created as optional. When a property is not optional, you won’t be able to save the managed object back to the store until the non-optional properties have a valid value.

Indexed properties are optimized for search efficiency at the cost of additional storage space in the underlying persistent store. This additional space required for the index will range in size depending on how much data needs indexing. If you’re not going to search on a particular attribute, you can save space by not indexing the attribute

用Binary Data时:

Allows External Storage is used to permit large binary data attribute values to be stored outside the persistent store. It is recommended that you enable this option when storing large media such as photos, audio, or video. Core Data will automatically store attribute
values over 1MB outside an SQLite persistent store when this option is enabled. This option has no effect when the underlying persistent store is XML (remember, this type of store isn’t supported on iOS).

Index in Spotlight doesn’t do anything for an iOS application. It is used to integrate a Core Data–based Mac application with Spotlight

Store in External Record File duplicates data from the persistent store into an XML representation outside the store.

Scalar Properties for Primitive Data Types

When you created an NSManagedObject subclass for the Item entity, you came across the option Use scalar properties for primitive data types. This option allows the resulting NSManagedObject subclass to use object properties only when it has no other recourse. Here’s a summary of how entity attributes translate to managed object properties when this option is selected:
■ A Date attribute becomes an NSTimeInterval.
■ A Double attribute becomes a double.
■ A Float attribute becomes a float.
■ An Integer 16/32/64 attribute becomes an int16_t, int32_t, or int64_t, respectively.
■ A Boolean attribute becomes a BOOL.