3

我现在有一个搜索页面,它将加载网络服务的结果列表,但是当我返回搜索页面时,我想“保存输入的任何内容(例如“resto italian”),然后将该条目和以前的条目显示到下面的表格视图中,如下图所示:

在此处输入图像描述

我的计划是使用属性列表序列化 - 如果还没有列表,则创建一个名为 history.plist 的属性列表,并用所做的每个搜索词填充它,并在上面的表格视图中显示最接近的十个。

我试过的:

// 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

我会在评论中使用我的建议,但在此期间对您的代码进行一些编辑可能会有所帮助。

        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

通过以下方式替换您的 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

我将使用Core Data,创建一个类,即分别HistoryRecord具有属性termSearchedtimestamp类型的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

在搜索动作中,只需将搜索结果保存到 NSUserDefaults 即可。

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

然后为表数据源加载相同的数组,并在 viewwillappear 和键盘关闭时重新加载表。

于 2013-02-28T18:18:32.410 回答
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 回答