CoreData

#import "ViewController.h"app

#import "User.h"fetch

@interface ViewController ()spa


@end .net


@implementation ViewController3d


- (void)viewDidLoad {orm

    [super viewDidLoad];ip

    [self insertData:@"Jack" withAge:@17 ];get

    [self insertData:@"Rose" withAge:@16];it

    [self insertData:@"Lily" withAge:@12];io

  

    [self selectData];

    

}


-(void)insertData:(NSString *)userName withAge:(NSNumber *)userAge{

    _app = [UIApplication sharedApplication].delegate;

    

    User *user = [NSEntityDescription insertNewObjectForEntityForName:@"User" inManagedObjectContext:self.app.managedObjectContext];

    

    [user setUserAge:userAge];

    [user setUserName:userName];

    BOOL hello = [_app.managedObjectContext save:nil];

    

    

    if(!hello){

        NSLog(@"出錯了");

    }

    else{

        NSLog(@"Success");

         NSLog(@"1111");

    }

    

}





-(void)deleteData{

    _app = [UIApplication sharedApplication].delegate;

    

    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"User"];

    

    NSArray *arrayData = [_app.managedObjectContext executeFetchRequest:request error:nil];

    NSLog(@"-----%@",arrayData);

    

    for(User *user in arrayData){

        if([user.userAge isEqualToNumber:@32]){

                        [_app.managedObjectContext save:nil];


            user.userName  = @"neil";

        }

        else{

            [_app.managedObjectContext deleteObject:user];


            [_app.managedObjectContext save:nil];

        }

    }

}



-(void)selectData{

    

    _app = [UIApplication sharedApplication].delegate;

    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"User"];

    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"userAge" ascending:NO];

    

    NSArray *sortArray = @[sort];

    

    NSPredicate *pr = [NSPredicate predicateWithFormat:@"userAge !=0"];

    

    request.predicate = pr;

    

    request.sortDescriptors = sortArray;

    

    NSArray *arrayData = [_app.managedObjectContext executeFetchRequest:request error:nil];

    for(User *user in arrayData){

        NSLog(@"%@ --- %@",user.userName,user.userAge);

       

    }

}

- (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}


@end

相關文章
相關標籤/搜索