iOS中coreData的用法


//
//  ViewController.m
//  coredatademo002
//
//  Created by ganchaobo on 13-6-29.
//  Copyright (c) 2013年 ganchaobo. All rights reserved.
//

#import "ViewController.h"
#import <CoreData/CoreData.h>
#import "Person.h"
@interface ViewController ()

@property(nonatomic,retain) NSManagedObjectContext *context;
@end

@implementation ViewController

#pragma mark -生命周期方法
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self LoadData];
    
    //[self UdataData];
   // [self addData];
//[self deleteData];
  //  [self searchdata];
    //面向對象操作
    [self addPerson];
    [self searchPerson];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewDidUnload{
    [super viewDidUnload];
    self.context=nil;
}
- (void)dealloc
{
    [_context release];
    [super dealloc];
}

#pragma mark-加載數據方式

-(void)LoadData{
    //Nil表是從主bundles中加對應的模型實體
    NSManagedObjectModel *model=[NSManagedObjectModel mergedModelFromBundles:nil];
    for (NSEntityDescription *desc in model.entities) {
        NSLog(@"%@",desc.name);
    }
    //通過模型 和數據庫持久化
    NSPersistentStoreCoordinator *storeCoordinator=[[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
    //持久化到coredata中
    NSString *document= [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    document=[document stringByAppendingPathComponent:@"coredata.db"];
    NSURL *url=[NSURL fileURLWithPath:document];
    NSError *error=nil;
    [storeCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:url options:nil error:&error];
    if(error){
        NSLog(@"打開數據庫失敗");
        return;
    }
    
    self.context=[[[NSManagedObjectContext alloc] init] autorelease];
    self.context.persistentStoreCoordinator=storeCoordinator;
    
}

-(void)addData{
 
    //把實體對象和實體上下文相關聯
    for (int i=0; i<10; i++) {
        
    
    NSManagedObject *obj=[NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.context];
        NSString *name=[NSString stringWithFormat:@"gcb%i",i];
        int age=i;
    [obj setValue: name forKey:@"name"];
    [obj setValue:@(age) forKey:@"age"];
    
    //保存上下文中相關聯的對象即可
    }
        [self.context save:nil];
    
}

-(void)searchdata{
    NSFetchRequest *fetch=[NSFetchRequest fetchRequestWithEntityName:@"Person"];
    
    //排序
    NSSortDescriptor *sort=[NSSortDescriptor sortDescriptorWithKey:@"age" ascending:NO];
    fetch.sortDescriptors=@[sort];
    //加入查詢條件 age>20
//    fetch.predicate=[NSPredicate predicateWithFormat:@"age>%i",20];
    //加入like *c1"
    //fetch.predicate=[NSPredicate predicateWithFormat:@"name like %@",@"*cb1*"];
    NSArray *arr=[self.context executeFetchRequest:fetch error:nil];
    for (NSManagedObject *mode in arr) {
        NSString *name=[mode valueForKey:@"name"];
        int age =[[mode valueForKey:@"age"] intValue];
        NSLog(@"%zi--%@",age,name);
    }
}
//先查詢出要修改的數據
-(void)UdataData{
 //要操作那一張表
    NSFetchRequest *Fetch=[NSFetchRequest fetchRequestWithEntityName:@"Person"];
    //先創建排序描述,在排序
    NSSortDescriptor *sort=[NSSortDescriptor sortDescriptorWithKey:@"age" ascending:NO];
    Fetch.sortDescriptors=@[sort];
  //加入查詢條件
    Fetch.predicate=[NSPredicate predicateWithFormat:@"age>%i",5];
    //把條件加入到上下文進行操作,得到查詢集合
    NSArray * arr=[self.context executeFetchRequest:Fetch error:nil];
    for (NSManagedObject *obj in arr) {
    //更改實體的數據
        [obj setValue:@(50) forKey:@"age"];
    }
    //同步更數據庫相關聯的數據
    [self.context save:nil];
    
    
    
}

//刪除數據, 從數據庫中取出來的對象,叫做NSManaedObject對象
-(void)deleteData{
    //要找出上下文中操作的一張表
    NSFetchRequest *FectchRequest=[NSFetchRequest fetchRequestWithEntityName:@"Person"];
    FectchRequest.predicate=[NSPredicate predicateWithFormat:@"age<%i",50];
    NSArray *arr=[self.context executeFetchRequest:FectchRequest error:nil];
    for (NSManagedObject *obj in arr) {
        [self.context deleteObject:obj];
    }
    //同步數據庫
    [self.context save:nil];
}

#pragma mark-面向對象開發
-(void)addPerson{
    //把要插入的實體和當前上下文相關聯
    Person *ps=[NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.context];
    ps.name=@"mj__itcast";
    ps.age=@28;
    //同步數據和上下文相關聯的
    [self.context save:nil];
}
-(void)searchPerson{
    NSFetchRequest *FetchRequest=[NSFetchRequest fetchRequestWithEntityName:@"Person"];
    NSArray *arr=[self.context executeFetchRequest:FetchRequest error:nil];
    for (Person *ps in arr) {
        NSLog(@"name=%@,age=%@",ps.name,ps.age);
    }
}
@end

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM