3

現時点では、Web サービスの結果のリストをロードする検索ページがありますが、検索ページに戻ったときに、入力した内容 (「resto italian」など)を「保存」したいと思います。次の画像のように、そのエントリと前のエントリを下のテーブル ビューに表示します。

ここに画像の説明を入力

私の計画は、プロパティ リストのシリアル化を使用することでした。リストがまだない場合は、history.plist という名前のプロパティ リストを作成し、作成された各検索語を入力して、上記のようにテーブル ビューに最も近い 10 個を表示します。

私が試したこと:

// should create history.plist
- (NSString *)dataFilePath {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    return [documentsDirectory stringByAppendingString:@"history.plist"];
}

/* This is the action for when 'search' is clicked - calls the method above to create 
a new plist if it's not already created. 
I then try to display the contents of the of the file in the textfield itself 
(for testing purposes) but it's not saving/displaying properly at the moment. */

- (IBAction)saveHistory:(id)sender {        
    NSString *filePath = [self dataFilePath];
    if([[NSFileManager defaultManager] fileExistsAtPath:filePath])
    {
       NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
       for (int i = 0; i < (sizeof(array)); i++) {
            UITextField *theField = self.searchHistory;
            theField.text = [NSString stringWithFormat:@"%@", array];
       }
    }        
    UIApplication *app = [UIApplication sharedApplication];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:app];        
}

これを試みているチュートリアルへのリンク、何をすべきかについての提案、または私が持っているものの改善は大歓迎です。

4

5 に答える 5

0

saveHistory 関数を以下の方法で置き換えます。

- (IBAction)saveHistory:(id)sender
{
      NSMutableArray *values = [[NSMutableArray alloc]initWithContentsOfFile:[self dataFilePath]];
      if(searchInputTextField.text.length > 0)
           [values addObject:searchInputTextField.text];
      [values writeToFile:[self dataFilePath] atomically:YES];

      [leTableView reloadData];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
     return values.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
     static NSString *CellIdentifier = @"Cell";
     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
     if (cell == nil)
     {
         cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
     }
     cell.textLabel.text = [values objectAtIndex:indexPath.row];
}
于 2013-02-27T06:01:16.103 に答える
0

コメントで私の提案を使用しますが、その間に役立つ可能性のあるコードの編集を次に示します。

        NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
        for (int i = 0; i <array.count; i++) {
            //I don't know what this line means
            UITextField *theField = self.searchHistory;
            //Change this line to this
            theField.text = [NSString stringWithFormat:@"%@", [array objectAtIndex:i]];
        }
于 2013-02-22T15:30:12.010 に答える
0

私は Core Data を使用してクラスを作成します。つまりHistoryRecord、属性termSearchedを持ちtimestamp、それぞれ NSString と NSDate 型のクラスを作成します。

#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>

@interface HistoryRecordManagedObject : NSManagedObject

@property (nonatomic, retain) NSString *termSearched;
@property (nonatomic, retain) NSDate *timestamp;

+ (NSArray *)findEntity:(NSString *)entity withPredicate:(NSPredicate *)predicate

@end

実装

#import "HistoryRecordManagedObject.h"

@implementation HistoryRecordManagedObject

@dynamic termSearched;
@dynamic timstamp;

+ (NSArray *)findEntity:(NSString *)entity withPredicate:(NSPredicate *)predicate
{
    NSError *error;
    NSArray *fetchedObjects;

        /* After set all properties, executes fetch request */
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entityDesc = [NSEntityDescription entityForName:entity
                                                      inManagedObjectContext:managedObjectContext];
        [fetchRequest setEntity:entityDesc];
        [fetchRequest setPredicate:predicate];

        fetchedObjects = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
        [fetchRequest release];


    return fetchedObjects;
}

@end

もちろんこれだけじゃない!モデルの作成など、Core Data を使用するには、いくつかの追加作業を行う必要があります。それについて少し読んでください!それは価値があります!

幸運を!

于 2013-02-27T14:49:40.917 に答える
0

これで問題が解決するはずです:

// This is inside viewDidLoad    
UIApplication *myApp = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self     
          selector:@selector(applicationDidEnterBackground:)                                                                
          name:UIApplicationDidEnterBackgroundNotification
          object:myApp];

// This is inside my table view - where I'm loading the file data to display in table cells
NSString *myPath = [self dataFilePath];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:myPath];
if (fileExists) {
   NSArray *values = [[NSArray alloc] initWithContentsOfFile:myPath];
      for (int i = 0; i < values.count; i++) {
         cell.historyDisplay.text = [NSString stringWithFormat:@"%@", [values objectAtIndex:i]];
      }
}

// This is the file path for history.plist
- (NSString *)dataFilePath {
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    return [[path objectAtIndex:0] stringByAppendingString:@"history.plist"];
}

// This is my search button - I want to save whatever was typed in the text field, into history.plist, to display in my tableview whenever a user goes to it.     
- (IBAction)saveHistory:(id)sender {
    NSMutableArray *values = [[NSMutableArray alloc]initWithContentsOfFile:[self dataFilePath]];
    if(searchInputTextField.text.length > 0)
         [values addObject:searchInputTextField.text];
    [values writeToFile:[self dataFilePath] atomically:YES];    
    [leTableView reloadData];
}
于 2013-04-30T08:35:25.330 に答える
0

検索のアクションでは、検索結果を NSUserDefaults に保存するだけです。

    NSMutableArray *searches = [[NSUserDefaults standardUserDefaults] arrayForKey:@"searches"];
[searches insertObject:textField.text atIndex:0];
[[NSUserDefaults standardUserDefaults] setObject:searches forKey:@"searches"];
[[NSUserDefaults standardUserDefaults] synchronize];

次に、テーブル データ ソースに同じ配列をロードし、キーボードが閉じられたときにビューにテーブルを再ロードします。

于 2013-02-28T18:18:32.410 に答える