Two separate UITableViews in two separate controller, loading the same data - iphone

first .h
#interface PersonnelViewController : UIViewController
<UITableViewDelegate, UITableViewDataSource>
{
NSMutableArray *personnelData;
IBOutlet UITextField *tableCellText;
IBOutlet UITableView *personTableView;
IBOutlet UINavigationItem *navItem;
}
#property (nonatomic, retain) NSMutableArray *personnelData;
-(IBAction)addRowToTableView;
-(IBAction)editTable;
-(NSString *)personDataFilePath;
-(IBAction)endText;
-(IBAction)done;
first .m
#implementation PersonnelViewController
#synthesize personnelData;
-(IBAction)done{
[self dismissModalViewControllerAnimated:YES];
}
- (void)viewDidLoad {
NSArray *archivedArray = [NSKeyedUnarchiver unarchiveObjectWithFile:[self personDataFilePath]];
if (archivedArray == nil) {
personnelData = [[NSMutableArray alloc] init];
} else {
personnelData = [[NSMutableArray alloc] initWithArray:archivedArray];
}
}
- (IBAction)addRowToTableView {
[personnelData addObject:tableCellText.text];
[self personDataFilePath];
[personTableView reloadData];
}
- (IBAction)editTable {
UIBarButtonItem *leftItem;
[personTableView setEditing:!personTableView.editing animated:YES];
if (personTableView.editing) {
leftItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(editTable)];
} else {
leftItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:#selector(editTable)];
}
navItem.rightBarButtonItem = leftItem;
[self personDataFilePath];
[personTableView reloadData];
}
- (IBAction)endText {
}
- (NSInteger)numberOfSectionInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [personnelData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Cell"] autorelease];
}
cell.textLabel.text = [personnelData objectAtIndex:indexPath.row];
return cell;
}
- (NSString *)personDataFilePath {
NSString *personDataFilePath;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
personDataFilePath = [[documentDirectory stringByAppendingPathComponent:#"applicationData.plist"] retain];
return personDataFilePath;
}
- (void)saveData1 {
[NSKeyedArchiver archiveRootObject:[personnelData copy] toFile:[self personDataFilePath]];
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
[personnelData removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationTop];
}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
return YES;
}
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath
toIndexPath:(NSIndexPath *)toIndexPath {
NSString *item = [[personnelData objectAtIndex:fromIndexPath.row] retain];
[personnelData removeObject:item];
[personnelData insertObject:item atIndex:toIndexPath.row];
[item release];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
- (void)dealloc {
[super dealloc];
}
#end
Second .h
#interface ApparatusViewController : UIViewController
<UITableViewDelegate, UITableViewDataSource> {
NSMutableArray *apparatusData;
IBOutlet UITextField *tableCellText;
IBOutlet UITableView *mainTableView;
IBOutlet UINavigationItem *navItem;
}
#property (nonatomic, retain) NSMutableArray *apparatusData;
-(IBAction)addRowToTableView;
-(IBAction)editTable;
-(NSString *)apparatusDataFilePath;
-(IBAction)endText;
-(IBAction)done;
#end
Second .m
#implementation ApparatusViewController
#synthesize apparatusData;
-(IBAction)done{
[self dismissModalViewControllerAnimated:YES];
}
- (void)viewDidLoad {
NSArray *arichvedArray = [NSKeyedUnarchiver unarchiveObjectWithFile:[self apparatusDataFilePath]];
if (arichvedArray == nil) {
apparatusData = [[NSMutableArray alloc] init];
} else {
apparatusData = [[NSMutableArray alloc] initWithArray:arichvedArray];
}
}
- (IBAction)addRowToTableView {
[apparatusData addObject:tableCellText.text];
[self apparatusDataFilePath];
[mainTableView reloadData];
}
- (IBAction)editTable {
UIBarButtonItem *leftItem;
[mainTableView setEditing:!mainTableView.editing animated:YES];
if (mainTableView.editing) {
leftItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(editTable)];
} else {
leftItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:#selector(editTable)];
}
navItem.rightBarButtonItem = leftItem;
[self apparatusDataFilePath];
[mainTableView reloadData];
}
- (IBAction)endText {
}
- (NSInteger)numberOfSectionInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [apparatusData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Cell"] autorelease];
}
cell.textLabel.text = [apparatusData objectAtIndex:indexPath.row];
return cell;
}
- (NSString *)apparatusDataFilePath {
NSString *apparatusDataFilePath;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
apparatusDataFilePath = [[documentDirectory stringByAppendingPathComponent:#"applicationData.plist"] retain];
return apparatusDataFilePath;
}
- (void)saveData {
[NSKeyedArchiver archiveRootObject:[apparatusData copy] toFile:[self apparatusDataFilePath]];
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
[apparatusData removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
return YES;
}
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath
toIndexPath:(NSIndexPath *)toIndexPath {
NSString *item = [[apparatusData objectAtIndex:fromIndexPath.row] retain];
[apparatusData removeObject:item];
[apparatusData insertObject:item atIndex:toIndexPath.row];
[item release];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
- (void)dealloc {
[super dealloc];
}
#end
The data seems to be loading the same data into each table. How do I fix this.

You are loading "applicationData.plist" in both views!

Related

Accordion style tableview without using sections

I am interning for the summer on an iOS native app development team. They gave me a task of accomplishing removing/inserting cells in a tableview without using sections. I am struggling with the task if anyone could take a look at the code and try to help me out id be much appreciated. I am getting some removals and disappearances but it is not staying consistent, and it is adding cells that are already visible. (consistency in the sense that once i insert rows, row 3 is now row 5, and my modulo arithmetic gets thrown off.
I am very new to objective c so any advice / help would be much appreciated.
#implementation MasterViewController
NSMutableArray * levels;
NSMutableArray * array;
NSMutableIndexSet * expandedSections;
NSMutableDictionary * dict;
-(BOOL) loadFiles{
// NSFileManager * fileManager = [NSFileManager defaultManager];
if (!expandedSections) {
expandedSections = [[NSMutableIndexSet alloc]init];
}
array = [[NSMutableArray alloc]init];
levels = [[NSMutableArray alloc]init];
for (int i=0; i<20; i++) {
NSString * temp = [[NSString alloc]initWithFormat:#"This is row : %i ", i];
[array addObject:temp];
}
for (int i=0; i<20; i++) {
NSNumber * temp = [[NSNumber alloc]initWithInt:i];
[levels addObject:temp];
}
dict = [[NSMutableDictionary alloc]initWithObjects:array forKeys:levels];
NSLog(#"TEST: %#", [dict objectForKey:[levels objectAtIndex:1]]);
return YES;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(#"Master", #"Master");
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
[self loadFiles];
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem;
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(insertNewObject:)];
self.navigationItem.rightBarButtonItem = addButton;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)insertNewObject:(id)sender {
if (!_objects) {
_objects = [[NSMutableArray alloc] init];
}
[_objects insertObject:[NSDate date] atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
#pragma mark - Table View
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if ([expandedSections containsIndex:section]) {
return [array count] +2;
}
return [array count];
}
// Customize the appearance of table view cells.
- (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];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
if (!(indexPath.row %3)==0) {
cell.textLabel.text = [dict objectForKey:[levels objectAtIndex:indexPath.row]];
[cell setIndentationLevel:2];
cell.accessoryType = UITableViewCellAccessoryNone;
cell.accessoryView = nil;
} else {
cell.textLabel.text = [dict objectForKey:[levels objectAtIndex:indexPath.row]];
[cell setIndentationLevel:0];
}
return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the specified item to be editable.
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle: (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
[_objects removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationFade];
} else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (!self.detailViewController) {
self.detailViewController = [[DetailViewController alloc] initWithNibName:#"DetailViewController" bundle:nil];
}
BOOL currentlyExpanded = [expandedSections containsIndex:indexPath.row];
//[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSLog(#"CurrentlyExpanded : %d", currentlyExpanded);
NSLog(#"TEST: %#", [dict objectForKey:[levels objectAtIndex:indexPath.row ]]);
if ((indexPath.row %3)==0) {
// only first row toggles exapand/collapse
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSInteger section = indexPath.section;
BOOL currentlyExpanded = [expandedSections containsIndex:section];
NSInteger rows;
NSMutableArray *tmpArray = [NSMutableArray array];
if (currentlyExpanded) {
rows = 2;
[expandedSections removeIndex:section];
} else {
[expandedSections addIndex:section];
rows = 2;
}
for (int i=indexPath.row+1; i<=(indexPath.row + rows); i++) {
NSIndexPath *tmpIndexPath = [NSIndexPath indexPathForRow:i
inSection:section];
[tmpArray addObject:tmpIndexPath];
}
if (currentlyExpanded) {
[tableView deleteRowsAtIndexPaths:tmpArray
withRowAnimation:UITableViewRowAnimationTop];
} else {
[tableView insertRowsAtIndexPaths:tmpArray
withRowAnimation:UITableViewRowAnimationTop];
}
}
if ((indexPath.row %3)>0) {
NSDate *object = _objects[indexPath.row];
self.detailViewController.detailItem = object;
[self.navigationController pushViewController:self.detailViewController animated:YES];
}
}
#end
Take a look at TLIndexPathTools. It greatly simplifies building dynamic tables like this. It does all the work calculating and performing the batch updates for you. Try running the Outline sample project. It demonstrates how to build an expandable tree without using sections. You can accomplish what you need by just building up a two-level tree.

How to keep the checkmark in a UITableView after the view disappears

I have a uitableview that's displaying multiple selections with a custom checkmark. When selected the rows value is save using NSUserDefaults. The problem is that despite the values being saved the checkmarks disappear from the table cell rows. I can't figure out why.
thanks for any help, I'm really stuck on this.
Here's the .h code:
#interface CategoriesViewController : UITableViewController {
NSString *selectedCategoryTableString;
NSString *jsonStringCategory;
int prev;
}
// arForTable array will hold the JSON results from the api
#property (nonatomic, retain) NSArray *arForTable;
#property (nonatomic, retain) NSMutableArray *arForIPs;
#property (nonatomic, retain) NSMutableArray *categorySelected;
#property (nonatomic, retain) NSString *jsonStringCategory;
#property(nonatomic, retain) UIView *accessoryView;
#end
and the .m code:
#implementation CategoriesViewController
#synthesize jsonStringCategory;
#synthesize arForTable = _arForTable;
#synthesize arForIPs = _arForIPs;
- (void)viewDidLoad
{
[super viewDidLoad];
self.arForIPs=[NSMutableArray array];
self.categorySelected = [[NSMutableArray alloc] init];
[self reloadMain];
self.tableView.allowsMultipleSelection = YES;
}
-(void) reloadMain {
jsonString = #"http:///******";
// Download the JSON
NSString *jsonString = [NSString
stringWithContentsOfURL:[NSURL URLWithString:jsonString]
encoding:NSStringEncodingConversionAllowLossy|NSUTF8StringEncoding
error:nil];
NSMutableArray *itemsTMP = [[NSMutableArray alloc] init];
// Create parser
SBJSON *parser = [[SBJSON alloc] init];
NSDictionary *results = [parser objectWithString:jsonString error:nil];
itemsTMP = [results objectForKey:#"results"];
self.arForTable = [itemsTMP copy];
[self.tableView reloadData];
}
#pragma mark - Table view data source
- (int)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.arForTable 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];
[cell.textLabel setFont:[UIFont fontWithName: #"Asap-Bold" size: 14.0f]];
[cell.detailTextLabel setFont:[UIFont fontWithName: #"Asap-Bold" size: 14.0f]];
cell.accessoryView.hidden = NO;
}
UIImageView *cellAccessoryImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"icon-tick.png"]] ;
UIImageView *cellAccessoryNoneImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#""]] ;
if([self.arForIPs containsObject:indexPath]){
cell.accessoryView = cellAccessoryImageView;
} else {
cell.accessoryView = cellAccessoryNoneImageView;
}
// Get item from tableData
NSDictionary *item = (NSDictionary *)[_arForTable objectAtIndex:indexPath.row];
// encoding fix
NSString *utf8StringTitle = [item objectForKey:#"name"];
NSString *correctStringTitle = [NSString stringWithCString:[utf8StringTitle cStringUsingEncoding:NSISOLatin1StringEncoding] encoding:NSUTF8StringEncoding];
cell.textLabel.text = [correctStringTitle capitalizedString];
NSNumber *num = [item objectForKey:#"id"];
cell.detailTextLabel.text = [num stringValue];
cell.detailTextLabel.hidden = YES;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
if([self.arForIPs containsObject:indexPath]){
[self.arForIPs removeObject:indexPath];
[self.categorySelected removeObject:[[self.arForTable objectAtIndex:indexPath.row] objectForKey:#"id"]];
} else {
[self.arForIPs addObject:indexPath];
[self.categorySelected addObject:[[self.arForTable objectAtIndex:indexPath.row] objectForKey:#"id"]];
NSLog(#"%# categorySelected",self.categorySelected);
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSLog(#"%# defaults categorySelected",[defaults arrayForKey:#"selectedCategoryTableString"]);
NSString *string = [self.categorySelected componentsJoinedByString:#","];
[defaults setObject:string forKey:#"selectedCategoryTableString"];
NSLog(#"%# STRING",string);
}
[tableView reloadData];
}
-(void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:NO];
[self.navigationController setNavigationBarHidden:YES animated:NO];
self.navigationController.toolbarHidden = YES;
}
First of all your code has lots of memory leaks, please do use the static analyzer and/or instruments to fix them, few for them are pretty obvious like you initialized the SBJSON parser and did not release it, itemsTMP is another.
I have rewritten your code to be much more efficient and memory friendly:
#interface CategoriesViewController : UITableViewController
{
NSArray *_items;
NSMutableArray *_selectedItems;
UIImageView *cellAccessoryImageView;
}
#end
#implementation CategoriesViewController
- (void)viewDidLoad
{
[super viewDidLoad];
_selectedItems = [NSMutableArray new];
cellAccessoryImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"icon-tick.png"]] ;
[self reloadMain];
self.tableView.allowsMultipleSelection = YES;
}
- (void)reloadMain
{
NSString *jsonString = #"http:///******";
// Download the JSON
jsonString = [NSString
stringWithContentsOfURL:[NSURL URLWithString:jsonString]
encoding:NSStringEncodingConversionAllowLossy|NSUTF8StringEncoding
error:nil];
// Create parser
SBJSON *parser = [SBJSON new];
NSDictionary *results = [parser objectWithString:jsonString error:nil];
if (_items) [_items release];
_items = [[results objectForKey:#"results"] copy];
[parser release];
[self.tableView reloadData];
}
#pragma mark - Table view data source
- (int)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [_items 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];
[cell.textLabel setFont:[UIFont fontWithName: #"Asap-Bold" size: 14.0f]];
[cell.detailTextLabel setFont:[UIFont fontWithName: #"Asap-Bold" size: 14.0f]];
cell.accessoryView.hidden = NO;
}
NSDictionary *item = [_items objectAtIndex:indexPath.row];
if ([_selectedItems containsObject:item])
{
// preloaded image will help you have smoother scrolling
cell.accessoryView = cellAccessoryImageView;
}
else
{
cell.accessoryView = nil;
cell.accessoryType = UITableViewCellAccessoryNone;
}
// Get item from tableData
cell.textLabel.text = [[NSString stringWithCString:[[item objectForKey:#"name"] cStringUsingEncoding:NSISOLatin1StringEncoding] encoding:NSUTF8StringEncoding] capitalizedString];
cell.detailTextLabel.text = [[item objectForKey:#"id"] stringValue];
cell.detailTextLabel.hidden = YES;
item = nil;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSDictionary *item = [_items objectAtIndex:indexPath.row];
if ([_selectedItems containsObject:item])
{
[_selectedItems removeObject:item];
}
else
{
[_selectedItems addObject:item];
}
item = nil;
[tableView reloadRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
- (void)dealloc
{
[_selectedItems release];
[cellAccessoryImageView release];
[super dealloc];
}
#end
Since in your table there is only one section. Try this approach and this will help you certainly.
In - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath write following code;
if([self.arForIPs containsObject:[NSNumber numberWithInt:indexPath.row]]){
cell.accessoryView = cellAccessoryImageView;
} else {
cell.accessoryView = cellAccessoryNoneImageView;
}
And in - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath write code as below,
if([self.arForIPs containsObject:[NSNumber numberWithInt:indexPath.row]]){
[self.arForIPs removeObject:[NSNumber numberWithInt:indexPath.row]];
} else {
[self.arForIPs addObject:[NSNumber numberWithInt:indexPath.row]]
}

RSS parsing errors iPhone

I am building something that includes an RSS reader. Everything seems to work fine, except in every description (grabbed from the RSS feed using the code below), before the description, there is a "" How do I remove that?
#import "RSSItem.h"
#import "GTMNSString+HTML.h"
#implementation RSSItem
-(NSAttributedString*)cellMessage
{
if (_cellMessage!=nil) return _cellMessage;
NSDictionary* boldStyle = #{NSFontAttributeName: [UIFont fontWithName:#"Helvetica-Bold" size:16.0]};
NSDictionary* normalStyle = #{NSFontAttributeName: [UIFont fontWithName:#"Helvetica" size:16.0]};
NSMutableAttributedString* articleAbstract = [[NSMutableAttributedString alloc] initWithString:self.title];
[articleAbstract setAttributes:boldStyle
range:NSMakeRange(0, self.title.length)];
[articleAbstract appendAttributedString:
[[NSAttributedString alloc] initWithString:#"\n\n"]
];
int startIndex = [articleAbstract length];
NSString* description = [NSString stringWithFormat:#"%#<p><p><em>...", [self.description substringToIndex:200]];
description = [description gtm_stringByUnescapingFromHTML];
[articleAbstract appendAttributedString:
[[NSAttributedString alloc] initWithString: description]
];
[articleAbstract setAttributes:normalStyle
range:NSMakeRange(startIndex, articleAbstract.length - startIndex)];
_cellMessage = articleAbstract;
return _cellMessage;
}
#end
And this is the code for the MasterViewController.m file which displays the RSS feed:
#import "MasterViewController.h"
#import "DetailViewController.h"
#import "TableHeaderView.h"
#import "RSSLoader.h"
#import "RSSItem.h"
#interface MasterViewController () {
NSArray *_objects;
NSURL* feedURL;
UIRefreshControl* refreshControl;
}
#end
#implementation MasterViewController
-(void)refreshFeed
{
RSSLoader* rss = [[RSSLoader alloc] init];
[rss fetchRssWithURL:feedURL
complete:^(NSString *title, NSArray *results) {
dispatch_async(dispatch_get_main_queue(), ^{
[(TableHeaderView*)self.tableView.tableHeaderView setText:title];
_objects = results;
[self.tableView reloadData];
[refreshControl endRefreshing];
});
}];
}
-(void)viewDidLoad
{
[super viewDidLoad];
feedURL = [NSURL URLWithString:#"http://pipes.yahoo.com/pipes/pipe.run?_id=c47dcdc375e72c5ad08f3470eea6afa0&_render=rss"];
refreshControl = [[UIRefreshControl alloc] init];
[refreshControl addTarget:self
action:#selector(refreshInvoked:forState:)
forControlEvents:UIControlEventValueChanged];
[self.tableView addSubview: refreshControl];
[self refreshFeed];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
RSSItem *item = [_objects objectAtIndex:indexPath.row];
CGRect cellMessageRect = [item.cellMessage boundingRectWithSize:CGSizeMake(200,10000)
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
return cellMessageRect.size.height;
}
-(void) refreshInvoked:(id)sender forState:(UIControlState)state {
[self refreshFeed];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return _objects.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
RSSItem *object = _objects[indexPath.row];
cell.textLabel.attributedText = object.cellMessage;
cell.textLabel.numberOfLines = 5;
return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
RSSItem *object = _objects[indexPath.row];
self.detailViewController.detailItem = object;
}
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"showDetail"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
NSDate *object = _objects[indexPath.row];
[[segue destinationViewController] setDetailItem:object];
}
}
-(IBAction)btn_regPressed:(id)sender
{
NSLog(#"start to dissmis modal");
[self dismissViewControllerAnimated:YES completion:nil];
}
#end
Any ideas what is happening?
Replace the following code:
NSString* description = [NSString stringWithFormat:#"%#<p><p><em>...", [self.description substringToIndex:200]];
With:
NSString* description = [[NSString stringWithFormat:#"%#<p><p><em>...", [self.description substringToIndex:200]] stringByReplacingOccurrencesOfString:#"\"" withString:#""];

Search is not working

I'm trying to do search but its not working for me perfectly .What i need that when I enter B then i should get all the words that starts with B . I'm still wondering where i'm doing wrong. i'm very new to ios.
here is my code :-
ContactViewController.h
#import <UIKit/UIKit.h>
#interface ContactViewController :
UIViewController<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>
{
UISearchBar* searchBar;
IBOutlet UITableView* contactTableView;
NSMutableArray *listOfItems;
NSMutableArray *copyListOfItems;
NSArray *content;
NSArray *indices;
NSArray* contacts;
BOOL searching;
BOOL letUserSelectRow;
}
-(void)btn_AddContact;
#end
ContactViewController.m
#import "ContactViewController.h"
#import "AddContactsViewController.h"
#import "CustomCell.h"
#import "DataGenerator.h"
#interface ContactViewController ()
#end
#implementation ContactViewController
- (void)viewDidLoad
{
[super viewDidLoad];
const NSInteger searchBarHeight = 45;
searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320,
searchBarHeight)];
[self.view addSubview:searchBar];
searchBar.delegate = self;
[self.view addSubview:searchBar];
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithTitle:#"Refresh"
style:UIBarButtonItemStyleBordered target:self action:#selector(onAddContact)];
self.navigationItem.rightBarButtonItem = addButton;
UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont boldSystemFontOfSize:20.0];
label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
label.textAlignment = UITextAlignmentCenter;
label.textColor = [UIColor whiteColor]; // change this color
self.navigationItem.titleView = label;
label.text = NSLocalizedString(#"All Contacts", #"");
[label sizeToFit];
content = [DataGenerator wordsFromLetters];
indices = [[content valueForKey:#"headerTitle"] retain];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:
(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
#pragma mark -
#pragma mark Table view data source
// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [content count];
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:
(NSInteger)section {
return [[[content objectAtIndex:section] objectForKey:#"rowValues"] count] ;
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CellIdentifier];
}
if(searching) {
cell.textLabel.text = [copyListOfItems objectAtIndex:indexPath.row];
cell.detailTextLabel.text=[NSString stringWithFormat:#"%# %# %#",
#"pauline.abraham#gmail.com", #" |",#"123456777"] ;
}else {
cell.textLabel.text = [[[content objectAtIndex:indexPath.section]
objectForKey:#"rowValues"]
objectAtIndex:indexPath.row];
//cell.detailTextLabel.numberOfLines=2;
//cell.detailTextLabel.lineBreakMode=NSLineBreakByWordWrapping;
cell.detailTextLabel.text=[NSString stringWithFormat:#"%# %# %#",
#"pauline.abraham#gmail.com", #" |",#"123456777"] ;
}
return cell;
}
- (NSString *)tableView:(UITableView *)aTableView titleForHeaderInSection:
(NSInteger)section {
return [[content objectAtIndex:section] objectForKey:#"headerTitle"];
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
return [content valueForKey:#"headerTitle"];
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:
(NSString *)title atIndex:(NSInteger)index {
return [indices indexOfObject:title];
}
-(void)onAddContact
{
// AddContactsViewController* add = [[AddContactsViewController alloc]
initWithNibName:#"AddContactsViewController" bundle:nil];
// [self.navigationController pushViewController:add animated:YES];
}
-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
if(searching)
return;
searching = YES;
letUserSelectRow = NO;
[contactTableView setScrollEnabled:NO];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self
action:#selector(btn_DoneSearch)];
}
-(void)btn_DoneSearch
{
searchBar.text = #"";
[searchBar resignFirstResponder];
searching = NO;
letUserSelectRow = YES;
[contactTableView setScrollEnabled:YES];
self.navigationItem.rightBarButtonItem = nil;
[contactTableView reloadData];
}
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
//Remove all objects first.
[copyListOfItems removeAllObjects];
if([searchText length] > 0){
searching = YES;
letUserSelectRow = YES;
[contactTableView setScrollEnabled:YES];
[self searchTableView];
}else {
searching = NO;
letUserSelectRow = NO;
[contactTableView setScrollEnabled:NO];
}
[contactTableView reloadData];
}
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[self searchTableView];
}
-(void)searchTableView
{
NSString *searchText = searchBar.text;
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
for (NSDictionary *dictionary in content)
{
NSArray *array = [dictionary objectForKey:#"rowValues"];
[searchArray addObjectsFromArray:array];
}
for (NSString *sTemp in searchArray)
{
NSRange titleResultsRange = [sTemp rangeOfString:searchText
options:NSCaseInsensitiveSearch];
if (titleResultsRange.length>0)
{
[copyListOfItems addObject:sTemp];
NSLog(#"lenght : %d",titleResultsRange.length );
}
}
searchArray = nil;
}
#end
see this below code also you not add the rows related searched data put this condition in below 3 delegate method of UITableView also
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
if (searching)
return 1;
else
return [content count];
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (searching)
return [copyListOfItems count];
else
return [[[content objectAtIndex:section] objectForKey:#"rowValues"] count] ;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
if(searching)
return #"";
else
return [[content objectAtIndex:section] objectForKey:#"headerTitle"];
}

Single Text from two different UITableView

I have two UITableview's and if i select a one row in each table, the textLabel.text of that particular row should display in a single UIAlertview.
How can i combine the textLabel.textof two tables and display in one UIAlertView
Can anyone let me know how can i do this
EX: one Table view which displays A, B, C, D and one more tableView Which Shows 1,2,3,4.
This two table are from different class's. now suppose if i press a row in table 1 i will get textLabel.text as 'A' and if i press table 2 i will get textLabel.text as '1' now on the view if a select A in table1 and 1 in table 2 i should get a AlertView showing message as 'A1'
Code for reference:
viewController.h
#import <UIKit/UIKit.h>
#import "FirstTVContoller.h"
#import "SecondTVController.h"
#interface TwoTableViewsViewController : UIViewController<UITableViewDataSource, UITableViewDelegate>{
FirstTVContoller *firstController;
SecondTVController *secondController;
IBOutlet UITableView *firstTable;
IBOutlet UITableView *secondTable;
NSString *stringTable1;
NSString *stringTable2;
NSArray * myArray1;
NSArray * myArray2;
}
#property (nonatomic, retain) NSString *stringTable1;
#property (nonatomic, retain) NSString *stringTable2;
#property (nonatomic, retain) NSArray * myArray1;
#property (nonatomic, retain) NSArray * myArray2;
#end
.m:
#import "TwoTableViewsViewController.h"
#implementation TwoTableViewsViewController
#synthesize stringTable1 = stringTable1;
#synthesize stringTable2 = stringTable2;
#synthesize myArray1,myArray2;
- (void)viewDidLoad {
[super viewDidLoad];
if (firstController == nil) {
firstController = [[FirstTVContoller alloc] init];
}
if (secondController == nil) {
secondController = [[SecondTVController alloc] init];
}
[firstTable setDataSource:firstController];
[secondTable setDataSource:secondController];
[firstTable setDelegate:firstController];
[secondTable setDelegate:secondController];
firstController.view = firstController.tableView;
secondController.view = secondController.tableView;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
if (tableView == firstTable) {
self.stringTable1 = [myArray1 objectAtIndex: indexPath.row];
//call uiAlert, and place the stringTable1 on your message
if (tableView == secondTable) {
self.stringTable2 = [myArray2 objectAtIndex: indexPath.row];
//call uiAlert, and place the stringTable2 on your message
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"hi" message:[NSString stringWithFormat:#"%# %#", self.stringTable1, self.stringTable2] delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil, nil];
[alert show];
[alert release];
}}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[firstController release];
[secondController release];
[firstTable release];
[secondTable release];
[stringTable1 release];
[stringTable2 release];
[super dealloc];
}
#end
table1:
#import <Foundation/Foundation.h>
#interface FirstTVContoller : UITableViewController <UITableViewDataSource, UITableViewDelegate>{
NSMutableArray *items;
}
#end
#import "FirstTVContoller.h"
#import "SecondTVController.h"
#implementation FirstTVContoller
-(void) loadView
{
if (items == nil) {
items = [[NSMutableArray arrayWithObjects:#"1",#"2",#"3",#"4",#"5",#"6",#"6",#"8",#"9",#"10",#"11",#"12",#"13",#"14",#"15",#"16",#"17",nil] retain];
}
}
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger) tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section
{
return [items count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MyIdentifier"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewStylePlain reuseIdentifier:#"MyIdentifier"];
}
cell.textLabel.text = [NSString stringWithFormat:#"1.%#" ,[items objectAtIndex:indexPath.row]];
return cell;
}
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
NSString *stringVariable = cell.textLabel.text;
NSLog(#"%#",stringVariable);
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
return UITableViewCellEditingStyleDelete;
}
- (void)tableView:(UITableView *)tv commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath {
if(editingStyle == UITableViewCellEditingStyleDelete) {
//Delete the object from the table.
[items removeObjectAtIndex:indexPath.row];
[tv deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
-(void) dealloc
{
[items release];
[super dealloc];
}
#end
Table2:
#import <Foundation/Foundation.h>
#interface SecondTVController : UITableViewController <UITableViewDataSource, UITableViewDelegate>{
int numberOfCells;
}
#end
#import "SecondTVController.h"
#implementation SecondTVController
-(void) viewDidLoad
{
numberOfCells = 20;
}
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger) tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section
{
return numberOfCells;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MyIdentifier"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellSelectionStyleNone reuseIdentifier:#"MyIdentifier"];
}
cell.textLabel.text = [NSString stringWithFormat:#"2.%d", indexPath.row];
return cell;
}
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
NSString *stringVariable = cell.textLabel.text;
NSLog(#"%#",stringVariable);
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
return UITableViewCellEditingStyleDelete;
}
- (void)tableView:(UITableView *)tv commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath {
if(editingStyle == UITableViewCellEditingStyleDelete) {
//Delete the object from the table.
numberOfCells -=1;
[tv deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationRight];
}
}
#end
Kindly Suggest
Is not clear to me when you want your alertView shown,
but this will help you
you need to have a property for placing the text of your labels
so on your .h
# interface MyViewController :UIViewController {
NSString *_stringTable1;
NSString *_stringTable2;
}
#property (nonatomic, retain) NSString *stringTable1;
#property (nonatomic, retain) NSString *stringTable2;
on your .m
#synthesize stringTable1 = _stringTable1;
#synthesize stringTable2 = _stringTable2;
- (void) dealloc{
[_stringTable1 release];
[_stringTable2 release];
[super dealloc];
}
so on your table delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (tableView == table1) {
self.stringTable1 = [myArray1 objectAtIndex: indexPath.row];
//call uiAlert, and place the stringTable1 on your message
}
if (tableView == table2) {
self.stringTable2 = [myArray2 objectAtIndex: indexPath.row];
//call uiAlert, and place the stringTable2 on your message
}
}
when you call your uiAlertView, for the message you can just show them togheter like
[NSString stringWithFormat:#"%# %#", self.stringTable1, self.stringTable2];
//Combine two string in one string on the tap of second table cell tap event...
//Use following code in didSelectRowAtIndexPath method..and enjoy...
NSString *tempstring = [[NSString alloc]init];
tempstring =yourlable.text;// your cell label...
if (textField.tag == 1) {
NSUserDefaults *stringsaver = [NSUserDefaults standardUserDefaults];
if([stringsaver objectForKey:#"stringsaver"]== nil)
{
[stringsaver setObject:tempstring forKey:#"stringsaver"];
}
else
{
NSString *combinedstring = [stringsaver objectForKey:#"stringsaver"];
//NSLog(#"==%#",combinedstring);
UIAlertView *alertdata = [[UIAlertView alloc]
initWithTitle:#"Your Title"
message:combinedstring
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertdata show];
[alertdata release];
[stringsaver removeObjectForKey:#"stringsaver"];
}
Try this-
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell * cell1 = [tableView cellForRowAtIndexPath:indexPath];
// get here the instance of otherTableView.
UITableViewCell * cell2 = [otherTableView cellForRowAtIndexPath:indexPath];
UILabel *Title1 = (UILabel *)[cell1 viewWithTag:1]; //for it you need to make the label with Tag 1
UILabel *Title2 = (UILabel *)[cell2 viewWithTag:1]; //for it you need to make the label with Tag 1
NSString * str = [NSString stringWithFormat:#"%# %#",[Title1 text],[Title2 text]];
//fire the alert
UIAlertView *alertdata = [[UIAlertView alloc]
initWithTitle:#"Your Title"
message:str
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertdata show];
}