2012-04-17 10 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

答えて

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

ありがとうございました!今すぐもっと速く動作します:)私はこの方法で別のnsmutablearrayでそのfecthedObjects配列を与える場合、別の質問があります: [task addObjectsFromArray:fetchedObjects];私はfetledObjects配列を解放することができますか? – Piero

+0

NSArrayのallocを実行していません。この場合、リリースによってエラーが発生します。 – Frank

+0

申し訳ありませんが、NSPredicateでどのように関係のすべての要素を取得することができますか?最後の質問がありますか?あなたは私の質問でtaskes上の他のエンティティからの関係です... – Piero

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 = @ "新しいアプリ"; 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 *ステートメント。

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チャー* DBPATH = [DatabasePathにUTF8Stringを]。 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); 
} 
関連する問題