2012-04-17 69 views
0

我有核心數據的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上需要幾秒鐘來顯示該視圖,而在模擬器中速度很快,所以我的問題是,一個快速的方式,從核心日期獲取信息?我不知道有一個快速調用的屬性和值我想從核心數據檢索?

感謝

+0

看看NSPredicate,無需手動遍歷數據庫 – Frank 2012-04-17 13:24:54

回答

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]; 
+0

謝謝!現在工作更快:),我有另一個問題,如果我給這個fecthedObjects數組在另一個nsmutablearray這樣: [任務addObjectsFromArray:fetchedObjects];然後我可以釋放fetchedObjects數組? – Piero 2012-04-17 13:51:56

+0

你沒有爲NSArray做一個分配。在這種情況下發佈會導致錯誤。 – Frank 2012-04-17 13:56:21

+0

對不起,我有最後一個問題,如何與NSPredicate我可以檢索關係的所有元素?,你可以看到我的問題上面的任務是從另一個實體的關係... – Piero 2012-04-17 14:31:29

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); 

選擇數據庫: 常量字符* DBPATH = [databasePath UTF8字符串]; sqlite3_stmt *語句;

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); 
} 

刪除:

常量字符* DBPATH = [databasePath UTF8字符串]; sqlite3_stmt *語句;

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); 
}