快速访问Core Data数据库信息?

时间:2012-04-17 13:16:27

标签: iphone ios core-data nsfetchrequest

我有iOS应用程序的核心数据,在我的一个功能中我加载信息以这种方式显示我的应用程序的一个视图:

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription 
                               entityForName:@"MyDate" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];

NSError *error;

NSArray *fetchedObjects = [managedObjectContext executeFetchRequest:fetchRequest error:&error];

for (NSManagedObject *info in fetchedObjects) {

    if ([[[info valueForKey:@"status"] description] isEqualToString:@"Done"]) {

        NSArray *allTask = [[info valueForKey:@"taskes"] allObjects];
        for (NSManagedObject *task in allTask) {
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"yyyy-MM-dd"];

            if (IsDateBetweenInclusive([task valueForKey:@"firstDate"], fromDate, toDate)) {

                [taskArray addObject:task];
            }
        }
    }
}

所以我迭代所有数据库来查找信息然后显示它,当我的数据库中的信息很少时,上面的方法很快,但是当我的数据库中的信息更多时,在我的3GS上需要几秒钟来显示视图,而不是在模拟器中是快速的,所以我的问题是,有一个快速的方法,从核心日期获取信息?我不知道有一个快速调用属性和我想从核心数据中检索的值?

感谢

2 个答案:

答案 0 :(得分:2)

使用NSPredicate,请参阅https://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/CoreData/Articles/cdFetching.html

以下代码只会获取状态字段设置为'完成'

的值
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"MyDate" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"status == 'Done'"]];

NSError *error;

NSArray *fetchedObjects = [managedObjectContext executeFetchRequest:fetchRequest error:&error];

答案 1 :(得分:0)

创建database

NSString * docsDir;     NSArray * dirPaths;

dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

docsDir = [dirPaths objectAtIndex:0];
databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"newapp.sqlite"]];

NSFileManager *filemgr = [NSFileManager defaultManager];

if ([filemgr fileExistsAtPath: databasePath ] == NO)
{
    const char *dbpath = [databasePath UTF8String];

    if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
    {
        char *errMsg;
        const char *sql_stmt = "CREATE TABLE IF NOT EXISTS LIST (id VARCHAR, title VARCHAR , description VARCHAR ,date VARCHAR)";


        if ((sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK) )
        {
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Warning" message:@"Failed to create table" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];
                        }

        sqlite3_close(contactDB);

    } else {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Warning" message:@"Failed to open/create database" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];

    }
}

插入值

NSString * id_str = @“21”;     NSString * title = @“notisa”;     NSString * description = @“new app”;     NSString * date = @“21/4/30”;

const char *dbpath = [databasePath UTF8String];

if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK){
    // error handling...
}
// Construct the query and empty prepared statement.
const char *sql = "INSERT INTO `LIST` (`id`,`title`,`description`,`date`) VALUES (?, ?, ?, ?)";
sqlite3_stmt *statement;

   // UIImage *image = [UIImage imageWithData:imgdata];
//NSData *imageData=UIImagePNGRepresentation(image);

// Prepare the statement.
if (sqlite3_prepare_v2(contactDB, sql, -1, &statement, NULL) == SQLITE_OK) {
    // Bind the parameters (note that these use a 1-based index, not 0).


    sqlite3_bind_text(statement,1, [id_str UTF8String], -1, SQLITE_TRANSIENT);
    sqlite3_bind_text(statement,2, [title UTF8String], -1, SQLITE_TRANSIENT);
    sqlite3_bind_text(statement,3, [description UTF8String], -1, SQLITE_TRANSIENT);
    sqlite3_bind_text(statement,4, [date UTF8String], -1, SQLITE_TRANSIENT);

        }

// Execute the statement.
if (sqlite3_step(statement) != SQLITE_DONE) {
    // error handling...
    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Warning" message:@"Failed to Save" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
       }
else
{
    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Database" message:@"Stored Successfully" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
     }
// Clean up and delete the resources used by the prepared statement.
sqlite3_finalize(statement);
sqlite3_close(contactDB);

选择数据库:  const char * dbpath = [databasePath UTF8String];     sqlite3_stmt * statement;

if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
    NSString *querySQL = [NSString stringWithFormat: @"SELECT id,title,description,date FROM LIST"];

    const char *query_stmt = [querySQL UTF8String];

    if (sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
    {
        while(sqlite3_step(statement) == SQLITE_ROW)
        {
            NSLog(@"ROW-->%d",SQLITE_ROW);

            const char* policyNo  = (const char *)sqlite3_column_text(statement, 1);
            NSString *PolicyNumber = policyNo == NULL ? nil : [[NSString alloc]initWithUTF8String:policyNo];


            NSLog(@"PolicyNumber:%@",PolicyNumber);

            const char* start  = (const char *)sqlite3_column_text(statement, 2);
            NSString *startDate = start == NULL ? nil : [[NSString alloc]initWithUTF8String:start];

            const char* end  = (const char *)sqlite3_column_text(statement, 3);
            NSString *endDate = end == NULL ? nil : [[NSString alloc]initWithUTF8String:end];


                   }
        sqlite3_finalize(statement);
    }
    sqlite3_close(contactDB);
}

删除:

const char * dbpath = [databasePath UTF8String];     sqlite3_stmt * statement;

if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
    NSString *querySQL = [NSString stringWithFormat: @"DELETE id,title,description,date FROM LIST"];

    const char *query_stmt = [querySQL UTF8String];

    if (sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
    {
        while(sqlite3_step(statement) == SQLITE_ROW)
        {
            NSLog(@"ROW-->%d",SQLITE_ROW);

            const char* policyNo  = (const char *)sqlite3_column_text(statement, 1);
            NSString *PolicyNumber = policyNo == NULL ? nil : [[NSString alloc]initWithUTF8String:policyNo];


            NSLog(@"PolicyNumber:%@",PolicyNumber);

            const char* start  = (const char *)sqlite3_column_text(statement, 2);
            NSString *startDate = start == NULL ? nil : [[NSString alloc]initWithUTF8String:start];

            const char* end  = (const char *)sqlite3_column_text(statement, 3);
            NSString *endDate = end == NULL ? nil : [[NSString alloc]initWithUTF8String:end];


        }
        sqlite3_finalize(statement);
    }
    sqlite3_close(contactDB);
}