need to save contents of table view as txt file and the reload it later - objective-c

i need to be able to save the contents of my table view which is given data by an NSMutableArray to a txt file and then need to reopen that file automatically when the window containing the table view. i am making an application for mac
thanks
this is the code for the data source:
#import "tableViewData.h"
#import "Customer.h"
#implementation tableViewData
-(id) init
{
self = [super init];
if (self) {
list = nil;
filepath = #"/Users/Gautambir/Desktop/CustomerNames.txt";
if ([[NSFileManager defaultManager]fileExistsAtPath:filepath]) {
list = [[NSMutableArray alloc] initWithContentsOfFile:filepath];
}
else
list = [[NSMutableArray alloc]initWithObjects:name,memberNumber ,nil];
[list writeToFile:filepath atomically:YES];
}
return self;
}
-(NSInteger)numberOfRowsInTableView:(NSTableView *)tableView{
return [list count];
}
-(id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row{
Customer *Customer = [list objectAtIndex:row];
NSString *identifier = [tableColumn identifier];
return [Customer valueForKey:identifier];
}
-(void)tableView:(NSTableView *)tableView setObjectValue:(id)object forTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row{
Customer *Customer = [list objectAtIndex:row];
NSString *identifier = [tableColumn identifier];
[Customer setValue:object forKey:identifier];
}
-(void)save{
[list writeToFile:filepath atomically:YES];
}
-(IBAction)add:(id)sender{
[list addObject:[[Customer alloc]init]];
[tableView reloadData];
NSLog (#"array:%#",list);
}
-(IBAction)remove:(id)sender{
NSInteger row = [tableView selectedRow];
if (row != -1) {
[list removeObjectAtIndex:row];
}
[tableView reloadData];
}
-(void)dealloc
{
[super dealloc];
}
#end
and this is the .m file for the customer object class:
#import "Customer.h"
#implementation Customer
#synthesize name;
#synthesize memberNumber;
-(id) init
{
self = [super init];
if(self) {
name = #"Test";
int i = arc4random()%1000000000000000000;
if (i<0) {
memberNumber = i*-1;
}
else
memberNumber = i;
}
return self;
}
-(void)dealloc
{
[name release];
[super dealloc];
}
-(id)initWithCoder:(NSCoder *)aDecoder
{
self = [super init];
if (self)
{
name = [[aDecoder decodeObjectForKey:#"name"]retain];
memberNumber = [aDecoder decodeIntForKey:#"memberNumeber"];
}
return self;
}
-(void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:name forKey:#"name"];
[aCoder encodeInt:memberNumber forKey:#"memberNumber"];
}
#end
strong text

im sorry to post another answer - i misread the tags, and my first answer was relying to iOS.
this is the way to do it in OSX:
saving
NSMutableArray *array = ... //your array
[array addObject:...];
[array addObject:...];
[array addObject:...];
...
// then use an NSData to store the array
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:array];
NSString *path = #"/Users/User/path...";
[data writeToFile:path options:NSDataWritingAtomic error:nil];
retrieving
NSMutableArray *archive = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
sebastian

Related

NSPredicate custom object pointer

I have interfaces like:
#interface Isle
#property (nonatomic, strong) id index_one; //has to be an id ={
#property (nonatomic, strong) id index_two;
#end
#interface Item
#property (nonatomic, strong) NSString* name; //has to be an NSString
#end
Then I instantiate a search view controller:
#import "TableViewController.h"
#import "Isle.h"
#import "Item.h"
#interface TableViewController () <UISearchBarDelegate, UISearchDisplayDelegate>
#property (nonatomic, strong) NSArray* isles;
#property (nonatomic, strong) NSArray* filter;
#end
#implementation TableViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self)
{
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
Isle* isle_one = [[Isle alloc] init];
Isle* isle_two = [[Isle alloc] init];
Isle* isle_three = [[Isle alloc] init];
isle_one.index_one = [[Item alloc] init];
isle_one.index_two = [[Item alloc] init];
isle_two.index_one = [[Item alloc] init];
isle_two.index_two = [[Item alloc] init];
isle_three.index_one = [[Item alloc] init];
isle_three.index_two = [[Item alloc] init];
((Item*)isle_one.index_one).name = #"ketchup";
((Item*)isle_one.index_two).name = #"hot sauce";
((Item*)isle_two.index_one).name = #"butter";
((Item*)isle_two.index_two).name = #"cheese";
((Item*)isle_three.index_one).name = #"cereal";
((Item*)isle_three.index_two).name = #"rice";
_isles = [[NSArray alloc] initWithObjects: isle_one, isle_two, isle_three, nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSPredicate* res = [NSPredicate predicateWithFormat:#"(index_one.name contains[cd] %#) OR (index_two.name contains[cd] %#)", #"ketchup", #"hot sauce"];
_filter = [self.isles filteredArrayUsingPredicate: res];
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString scope:[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
return YES;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.searchDisplayController.searchResultsTableView)
{
return [[self filter] count];
}
return [[self isles] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:#"CellID" forIndexPath:indexPath];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"CellID"];
}
if (tableView == self.searchDisplayController.searchResultsTableView)
{
Isle* isle = (Isle*)[self.filter objectAtIndex: indexPath.row];
NSString* str = [NSString stringWithFormat:#"%#\t\t%#", ((Item*)isle.index_one).name, ((Item*)isle.index_two).name];
cell.textLabel.text = str;
return cell;
}
Isle* isle = (Isle*)[self.isles objectAtIndex: indexPath.row];
NSString* str = [NSString stringWithFormat:#"%# %#", ((Item*)isle.index_one).name, ((Item*)isle.index_two).name];
cell.textLabel.text = str;
return cell;
}
#end
But it says that it is not key-value compliant. Any ideas how I can accomplish this?
EDIT:
My exact error is:
Project1[1688:60b] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<NSSymbolicExpression 0x10e60a650> valueForUndefinedKey:]: this class is not key value coding-compliant for the key name.'
For filtering I did:
[arr filteredArrayUsingPredicate: res];

how to get information of an object instance from ID number

I have a program that has 2 tables on two different windows. One table holds the customer name and id number and the other one hold the item name and number. They are both stored in a array and also in a .plist file.
What i would like to do is that on a third page there is going to be a sales page where the user will enter the customer id and item id and the program should be able to find the name and display it to a label. I don't know where to start and go. Could somebody please help or show me how to do i? I can upload any code that anybody wants to see but as I dont know where to start I dont know what to upload.
this is the customer.h file
#import <Foundation/Foundation.h>
NSString *name;
int memberNumber;
#interface Customer : NSObject <NSCoding>
{
NSString *name;
int memberNumber;
}
#property (nonatomic, copy) NSString *name;
#property int memberNumber;
#end
this is the customer.m
#import "Customer.h"
#implementation Customer
#synthesize name;
#synthesize memberNumber;
-(id) init
{
self = [super init];
if(self)
{
name = #"Test";
int i = arc4random()%1000000000000000000;
if (i<0)
{
memberNumber = i*-1;
}
else
memberNumber = i;
}
return self;
}
- (id)initWithCoder:(NSCoder *)decoder
{
if (self = [super init])
{
self.name = [decoder decodeObjectForKey:#"name"];
self.memberNumber = [decoder decodeIntForKey:#"memberNumber"];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)encoder
{
[encoder encodeObject:name forKey:#"name"];
[encoder encodeInt:memberNumber forKey:#"memberNumber"];
}
-(void)dealloc
{
[name release];
[super dealloc];
}
#end
this is the tableView.h file
#import <Foundation/Foundation.h>
#include <stdlib.h>
NSString *filepath;
#interface tableViewData : NSObject <NSTableViewDataSource>
{
#private
IBOutlet NSTableView *tableView;
NSMutableArray *list;
NSString *filepath;
}
-(IBAction)add:(id)sender;
-(IBAction)remove:(id)sender;
#end
this is the tableView.m file
#import "tableViewData.h"
#import "Customer.h"
#implementation tableViewData
-(void)awakeFromNib{
filepath = #"/Users/Desktop/CustomerNames.plist";
if ([[NSFileManager defaultManager]fileExistsAtPath:filepath])
{
NSMutableArray *archive = [NSKeyedUnarchiver unarchiveObjectWithFile:filepath];
list = archive;
}
else
list=[[NSMutableArray alloc]init];
}
-(NSInteger)numberOfRowsInTableView:(NSTableView *)tableView
{
return [list count];
}
-(id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
{
Customer *Customer = [list objectAtIndex:row];
NSString *identifier = [tableColumn identifier];
return [Customer valueForKey:identifier];
}
-(void)tableView:(NSTableView *)tableView setObjectValue:(id)object forTableColumn: (NSTableColumn *)tableColumn row:(NSInteger)row
{
Customer *Customer = [list objectAtIndex:row];
NSString *identifier = [tableColumn identifier];
[Customer setValue:object forKey:identifier];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:list];
[data writeToFile:filepath options:NSDataWritingAtomic error:nil];
}
-(IBAction)add:(id)sender
{
[list addObject:[[Customer alloc]init]];
[tableView reloadData];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:list];
[data writeToFile:filepath options:NSDataWritingAtomic error:nil];
for (id name in list)
NSLog(#"obj: %#", name);
NSLog (#"array:%#",list);
}
-(IBAction)remove:(id)sender
{
NSInteger row = [tableView selectedRow];
if (row != -1)
{
[list removeObjectAtIndex:row];
}
[tableView reloadData];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:list];
[data writeToFile:filepath options:NSDataWritingAtomic error:nil];
}
-(void)dealloc
{
[super dealloc];
}
#end
hope this helps
(xcode 4.2.1 for OS X)
For example:
if([myNumber isKindOfClass:[NSNumber class]])
{
//do something here
}
That check if object myNumber is a NSNumber class Object. You can use whatever class you want of course. Read the documentation
If items you loaded to table are at the same order in your table you can use
[myArray objectAtIndex:[indexPath row]];
Then use can use the variables of the array that you needed.
First in that code:
-(void)tableView:(NSTableView *)tableView setObjectValue:(id)object forTableColumn: (NSTableColumn *)tableColumn row:(NSInteger)row
{
Customer *Customer = [list objectAtIndex:row];
NSString *identifier = [tableColumn identifier];
[Customer setValue:object forKey:identifier];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:list];
[data writeToFile:filepath options:NSDataWritingAtomic error:nil];
}
change Customer *Customer to Customer *customer ALWAYS use that way.
Then use that method to understand which row is selected.In your case which customer is selected. I understand from your code that every row has a costumer and those customers are in your list array.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//with this code you can get the selected customer from your list,
Customer *customer=[list objectAtIndex:[indexPath row]];
}
Then you can reach the values of the customer.

Reloading a table view after NSURLConnection succeeds

I'm new to Xcode, so bear with me:
I have a table view that I'm trying to reload once the NSURLConnection succeeds. I have a number of messages that help me guide me along the way... but when I call the reload upon the table view, the table doesn't repopulate.
JsonViewController.h:
#import <UIKit/UIKit.h>
#interface JsonViewController : UITableViewController {
NSMutableArray *theTweets;
IBOutlet UITableView *tview;
NSMutableData *responseData;
}
#property (nonatomic, retain) NSMutableArray *theTweets;
#property (nonatomic, retain) UITableView *tview;
#end
JsonViewController.m:
#import "JsonViewController.h"
#import "SBJson.h"
#implementation JsonViewController
#synthesize theTweets;
#synthesize tview;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void) dealloc {
[theTweets release];
[super dealloc];
}
- (NSMutableArray*)theTweets {
return [[theTweets retain] autorelease];
}
- (void) setTheTweets:(NSMutableArray *)newTweets {
if (newTweets != theTweets) {
[newTweets retain];
[theTweets release];
theTweets = newTweets;
NSLog(#"Setting new tweets...");
[tview reloadData];
}
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
tview.delegate = self;
responseData = [[NSMutableData data] retain];
theTweets = [NSMutableArray array];
NSURLRequest *request = [NSURLRequest requestWithURL:
[NSURL URLWithString:#"http://search.twitter.com/search.json?q=AriaPoker&result_type=recent"]];
[[NSURLConnection alloc] initWithRequest: request delegate:self];
NSLog(#"Trying to get feed upon initialization");
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
// methods that are not important
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
NSLog(#"Number of the tweets count at this point: %d", [theTweets count]);
return [theTweets count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
NSLog(#"Number of the tweets count at this point: %d", [theTweets count]);
// Configure the cell...
NSDictionary *aTweet = [theTweets objectAtIndex:[indexPath row]];
//cell.textLabel.text = [aTweet objectForKey:#"text"];
cell.textLabel.adjustsFontSizeToFitWidth = YES;
cell.textLabel.font = [UIFont systemFontOfSize:12];
cell.textLabel.numberOfLines = 4;
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.textLabel.text = #"Test";
cell.detailTextLabel.text = #"haha";
//NSURL *url = [NSURL URLWithString:[aTweet objectForKey:#"profile_image_url"]];
//NSData *data = [NSData dataWithContentsOfURL:url];
//cell.imageView.image = [UIImage imageWithData:data];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
NSLog(#"Loading cells in table");
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here. Create and push another view controller.
}
#pragma mark NSURLConnection Delegate Methods
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
//do nothing
NSLog(#"A connection error has occurred!");
}
- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSDictionary *results = [[responseString JSONValue] retain];
NSLog(#"Number of Rows: %d", [results count]);
NSMutableArray *allTweets = [results objectForKey:#"results"];
//[viewController setTweets:allTweets];
theTweets = allTweets;
NSLog(#"Number of misc2: %d", [theTweets count]);
[results release];
[tview reloadData];
}
#end
I'm wondering what I'm doing wrong here.
In connectionDidFinishLoading change from this:
theTweets = allTweets;
to this:
self.theTweets = allTweets;
or this way if you prefer:
[self setTheTweets:allTweets];
You weren't invoking the setter method, so it wasn't getting retained.
As suggested by progrmr try to call the setter method, or simply change definition of theTweets property to #dynamic theTweets in this case when you try to set property, the custom setter method will be called.

NSTableview and SearchField

I have an action for searching in NSMutableArray with name searcharray, which is equal to array with which NSTableView are connected.And I wrote a method for adding items to TableView just by sending NSMutableArray to my method.
The problem is that after searching if I delete what I have typed in SearchField and SearchField is empty, the compiler doesn't feel that it's empty and my TableView getting empty too, but due my code it's have to be with data from searcharray.
Here is my code:
#import "myTableViewAppDelegate.h"
#implementation myTableViewAppDelegate
#synthesize window;
#synthesize searcharray;
-(void)addItems:(NSMutableArray *)ar{
array = ar;
[array retain];
[tableView reloadData];
}
- (int)numberOfRowsInTableView:(NSTableView *)tableView{
return (int)[array count];
}
- (id)tableView:(NSTableView *)tableView
objectValueForTableColumn:(NSTableColumn *)tableColumn
row:(int)row
{
return [array objectAtIndex:row];
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
// Insert code here to initialize your application
NSMutableArray *animals = [[NSMutableArray arrayWithObjects:#"Cat", #"Dog", #"Fish", #"Squirrel", #"Bear", #"Turtle", nil] retain];
NSLog(#"%#",animals);
searcharray = animals;
[self addItems:animals];
}
- (IBAction)search:(id)sender {
//NSLog(#"%#",searcharray);
NSString *filter = [[NSString alloc] initWithString:[search stringValue]];
NSMutableArray *result = [[NSMutableArray alloc] init];
if (filter != nil) {
for (NSString *item in searcharray) {
if ([item rangeOfString:[search stringValue]].location !=NSNotFound ) {
NSLog(#"Item %# contains %#",item,[search stringValue]);
[result addObject:item];
}
}
}
else{
result = searcharray;
}
NSLog(#"%#",result);
[self addItems:result];
[result release];
[filter release];
}
#end
Fixed it.
if (filter != nil || filter.length != 0)
I don't know why, but just checking variable equal to NULL wasn't enough....

Invalid argument type to unary expression

I have this program with a tableView as my first view. I have also implemented (or at least tried to) a search bar on top of the view. Have used several hours to search for a solution, but without positive results.
#import "FirstViewController.h"
#import "NSDictionary-MutableDeepCopy.h"
#implementation FirstViewController
#synthesize listData, table, search, allNames, names, keys;
#pragma mark -
#pragma mark Custom Methods
- (void)resetSearch {
NSMutableDictionary *allNamesCopy = [self.allNames mutableDeepCopy];
self.names = allNamesCopy;
[allNamesCopy release];
NSMutableArray *keyArray = [[NSMutableArray alloc] init];
[keyArray addObjectsFromArray:[[self.allNames allKeys]
sortedArrayUsingSelector:#selector(compare:)]];
self.keys = keyArray;
[keyArray release];
}
-(void)handleSearchForTerm:(NSString *)searchTerm {
NSMutableArray *sectionsToRemove = [[NSMutableArray alloc] init];
[self resetSearch];
for (NSString *key in self.keys) {
NSMutableArray *array = [names valueForKey:key];
NSMutableArray *toRemove = [[NSMutableArray alloc] init];
for (NSString *name in listData) {
if ([name rangeOfString:searchTerm
options:NSCaseInsensitiveSearch].location == NSNotFound)
[toRemove addObject:name];
}
if ([array count] == [toRemove count])
[sectionsToRemove addObject:key];
[array removeObjectsInArray:toRemove];
[toRemove release];
}
[self.keys removeObjectsInArray:sectionsToRemove];
[sectionsToRemove release];
[table reloadData];
}
- (void)viewDidLoad {
NSString *path = [[NSBundle mainBundle] pathForResource:#"sortednames" ofType:#"plist"];
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
self.names = dict;
self.allNames = dict;
[dict release];
[self resetSearch];
[table reloadData];
[table setContentOffset:CGPointMake(0.0, 44.0)animated:NO];
self.parentViewController.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"background.png"]];
NSArray *array = [[NSArray alloc] initWithObjects:
// A larger amount of objects here.
self.listData = array;
[array release];
[super viewDidLoad];
}
/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
// Custom initialization
}
return self;
}
*/
/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
self.listData = nil;
self.table = nil;
self.search = nil;
self.allNames = nil;
self.names = nil;
self.keys = nil;
}
- (void)dealloc {
[listData release];
[search release];
[table release];
[allNames release];
[keys release];
[names release];
[super dealloc];
}
#pragma mark -
#pragma mark Table View Data Source Methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return ([keys count] > 0) ? [keys count] : 1;
}
- (NSInteger)tableView:(UITableView *)aTableView
numberOfRowsInSection: (NSInteger)section {
return [self.listData count];
if ([keys count] == 0)
return 0;
NSString *key = [keys objectAtIndex:section];
NSArray *nameSection = [names objectForKey:key];
return [nameSection count];
}
- (UITableViewCell *) extracted_method: (UITableViewCell *) cell {
return cell;
}
- (UITableViewCell *)tableView:(UITableView *)aTableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSUInteger section = [indexPath section];
NSUInteger row = [indexPath row];
NSString *key = [keys objectAtIndex:section];
NSArray *nameSection = [names objectForKey:key];
static NSString *sectionsTableIdentifier = #"sectionsTableIdentifier";
UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:
sectionsTableIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier: sectionsTableIdentifier] autorelease];
}
cell.backgroundColor = [UIColor clearColor];
cell.textColor = [UIColor whiteColor];
cell.detailTextLabel.textColor = [UIColor whiteColor];
cell.text = [nameSection objectAtIndex:row];
[self extracted_method: cell].text = [listData objectAtIndex:row];
return cell;
}
- (NSString *)tableView:(UITableView *)tableView
titleForHeaderInSection:(NSInteger)section {
if ([keys count] == 0)
return nil;
NSString *key = [keys objectAtIndex:section];
return key;
}
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
return keys;
}
#pragma mark -
#pragma mark Table View Delegate Methods
- (NSIndexPath *)tableView:(UITableView *)tableView
willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[search resignFirstResponder];
return indexPath;
}
#pragma mark -
#pragma mark Search Bar Delegate Methods
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
NSString *searchTerm = [searchBar text];
[self handleSearchForTerm:searchTerm];
}
- (void)searchBar:(UISearchBar *)searchBar
textDidChange:(NSString *)searchTerm {
if ([searchTerm length] == 0) {
[self resetSearch];
[table reloadData];
return;
}
[self handleSearchForTerm:searchTerm];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
search.text = #"";
[self resetSearch];
[table reloadData];
[searchBar resignFirstResponder];
}
#end
Ok guys. My problem is that this doesnt get the search function to work. In addition I receive siginal SIGABRT at this line:
NSString *key = [keys objectAtIndex:section];
So I need help with two things:
1: I need to get that SIGABRT away.
Error log message: * Terminating app due to uncaught exception
'NSRangeException', reason: '* -[NSMutableArray objectAtIndex:]:
index 0 beyond bounds for empty array'
That is I don't store any data in keys. how would I do that? and what would I store?
2: Want the search function to search in my listData array!
Thanks in advance - hope u can help!
You have not finished your sectionIndexTitlesForTableView: method. Right now it is:
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
return keys;
There is no closing }, so the compiler thinks everything after that is still part of that method. When you try to define the next method, use use - (NSIndexPath *) to indicate that it is an instance method which returns NSIndexPath*, but the compiler thinks you are trying to subtract something.
The solution is simple: Add the } to the end of sectionIndexTitlesForTableView:.
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
return keys;
}