在iOS中实现搜索历史功能

时间:2013-02-22 15:14:01

标签: iphone ios objective-c cocoa-touch serialization

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

enter image description here

我的计划是使用属性列表序列化 - 如果还没有列表,则创建一个名为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 个答案:

答案 0 :(得分: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]];
        }

答案 1 :(得分: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];
}

答案 2 :(得分: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需要做一些额外的事情,比如创建模型。仔细阅读一下吧!值得!

祝你好运!

答案 3 :(得分: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];
}
相关问题