RSS parsing errors iPhone - 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:#""];

Related

Xcode live news feed with multiple accounts or user

Im new to xcode.
and Im creating this facebook, twitter, instagram and youtube news feed in a tableview
at first Im trying this facebook to load multiple json
#import "ViewController.h"
#import "DetailViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#define kQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
#define kJSONUrl [NSURL URLWithString:#"https://www.facebook.com/feeds/page.php?id=1387524391527078&format=json"]
#define kJSONUrl1 [NSURL URLWithString:#"https://www.facebook.com/feeds/page.php?id=196934133652011&format=json"]
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
#interface ViewController ()
#end
#implementation ViewController
#synthesize jsonTitles,table,jsonContent;
-(void)loadJSON:(NSData *)responseData {
NSError *error;
NSArray *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSArray *array = [json valueForKey:#"entries"];
for (int i = 0; i < array.count; i++) {
NSArray *entry = [array objectAtIndex:i];
NSString *title = [entry valueForKey:#"title"];
NSString *content = [entry valueForKey:#"content"];
[jsonTitles addObject:title];
[jsonContent addObject:content];
}
[self.table reloadData];
}
- (void)viewDidLoad
{
self.table.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"background.png"]];
jsonTitles = [[NSMutableArray alloc]init];
jsonContent = [[NSMutableArray alloc]init];
dispatch_async(kQueue, ^{
NSData *data = [NSData dataWithContentsOfURL:kJSONUrl];
[self performSelectorOnMainThread:#selector(loadJSON:) withObject:data waitUntilDone:YES];
NSData *data1 = [NSData dataWithContentsOfURL:kJSONUrl1];
[self performSelectorOnMainThread:#selector(loadJSON:) withObject:data1 waitUntilDone:YES];
});
[super viewDidLoad];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 40;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [jsonTitles count];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[self performSegueWithIdentifier:#"detailSegue" sender:nil];
// NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:#"detailSegue" ascending:YES];
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"detailSegue"]) {
DetailViewController *detail = segue.destinationViewController;
NSIndexPath *path = [self.table indexPathForSelectedRow];
detail.titleText = [jsonTitles objectAtIndex:path.row];
detail.contentText = [jsonContent objectAtIndex:path.row];
}
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *tableCellID = #"tableCellID";
// UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:tableCellID];
UITableViewCell *cell =[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:tableCellID];
NSString *myurl = #"http://graph.facebook.com/idoltap/picture";
NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:myurl]];
UIImage *myimage = [[UIImage alloc] initWithData:imageData];
cell.imageView.image = myimage;
// cell.imageView.image = [UIImage imageNamed:#"background.png"];
cell.textLabel.text = #"iDOLTap";
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tableCellID];
}
cell.detailTextLabel.text = [jsonTitles objectAtIndex:indexPath.row];
if ([cell.detailTextLabel.text isEqual: #" "]) {
cell.detailTextLabel.text = [jsonContent objectAtIndex:indexPath.row];
}
return cell;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Is my pattern correct?
I dont know how I can load the right profile picture for each json/user and sort it by its published date.
I just want some help to fix this one in the right way.

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]]
}

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"];
}

UITableView - methods are not being called

I have a subview in which I build a UITableview, I've set the delegate and datasource to the subview but for some reason the table methods are not being called...can someone look over my code and see what I am doing wrong? Thanks
.h file
#interface TwitterController : UIView <UITableViewDelegate, UITableViewDataSource> {
UIButton* btnCloseView;
UITableView* tblTweets;
UIImageView* imgTwitterIcon;
ColorController* colorManager;
NSMutableArray* tweetsArray;
NSMutableArray* tableData;
NSString* twitterID;
}
#property (nonatomic, retain) NSString* twitterID;
- (NSMutableArray* ) getTweets;
- (void) sendNotification : (id) sender;
#end
.m file
#import "TwitterController.h"
#implementation TwitterController
#synthesize twitterID;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
colorManager = [ColorController new];
}
return self;
}
/*- (void)drawRect:(CGRect)rect {
}*/
- (void)layoutSubviews {
imgTwitterIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"imgTwitterBird"]];
CGRect twitterIconFrame = [imgTwitterIcon frame];
twitterIconFrame.origin.x = 50.0;
twitterIconFrame.origin.y = 20.0;
tblTweets = [[UITableView alloc] initWithFrame:CGRectMake(50.0, 25.0, 220.0, 500.0)];
tblTweets.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
tblTweets.separatorColor = [colorManager setColor:176.0:196.0:222.0];
tblTweets.layer.borderWidth = 1.0;
tblTweets.rowHeight = 20.0;
tblTweets.scrollEnabled = YES;
tblTweets.delegate = self;
tblTweets.dataSource = self;
tableData = [self getTweets];
UIImage* imgCloseButton = [UIImage imageNamed:#"btnCloseWindow.png"];
CGSize imageSize = imgCloseButton.size;
btnCloseView = [[UIButton alloc] initWithFrame: CGRectMake(220.0, 550.0, imageSize.width, imageSize.height)];
[btnCloseView setImage:[UIImage imageNamed:#"btnCloseWindow.png"] forState:UIControlStateNormal];
[btnCloseView addTarget:self action:#selector(sendNotification:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:tblTweets];
[self addSubview:imgTwitterIcon];
[self addSubview:btnCloseView];
}
- (NSMutableArray*) getTweets {
//array to hold tweets
tweetsArray = [[NSMutableArray alloc] init];
twitterID = #"Pruit_Igoe";
///set up a NSURL to the twitter API
NSURL* twitterAPI = [NSURL URLWithString:[NSString stringWithFormat:#"https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=%#&count=10", twitterID]];
//get last 10 tweets (max is 20)
TWRequest *twitterRequest = [[TWRequest alloc] initWithURL:twitterAPI
parameters:nil requestMethod:TWRequestMethodGET];
// Notice this is a block, it is the handler to process the response
[twitterRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
if ([urlResponse statusCode] == 200) {
// The response from Twitter is in JSON format
// Move the response into a dictionary and print
NSError *error;
NSDictionary *tweetsDict = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
for(NSDictionary* thisTweetDict in tweetsDict) {
[tweetsArray addObject:[thisTweetDict objectForKey:#"text"]];
}
}
else
NSLog(#"Twitter error, HTTP response: %i", [urlResponse statusCode]);
}];
return tweetsArray;
}
#pragma mark Table Management
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [tableData count];
NSLog(#"%i", [tableData count]); //does not log!
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [tableData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"tableCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.textColor = [UIColor colorWithRed:66.0/255.0 green:66.0/255.0 blue:66.0/255.0 alpha:1];
cell.textLabel.font = [UIFont fontWithName:#"Helvetica-Bold" size: 13.0];
cell.textLabel.text = [tweetsArray objectAtIndex:indexPath.row];
CGRect cellFrame = [cell frame];
cellFrame.size.height = 25.0;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSString* thisTweet = [tableData objectAtIndex:indexPath.row];
}
#pragma mark Close Window
- (void) sendNotification : (id) sender {
NSMutableDictionary* userData = [[NSMutableDictionary alloc] init];
[userData setObject:#"closeTwitter" forKey:#"theEvent"];
[[NSNotificationCenter defaultCenter] postNotificationName:#"theMessenger" object:self userInfo: userData];
}
#end
I think you are not allocate and initialize tableData. Write it tableData = [[NSMutableArray alloc] init]; in - (id)initWithFrame:(CGRect)frame method or - (void)layoutSubviews method. Just try it.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
NSLog(#"%i", [tableData count]);
return [tableData count];
//NSLog(#"%i", [tableData count]); //does not log!
}
If the output is zero, tableData array is empty. Check it tableData array
You should do all the initialization (tblTweets for example) in initWithFrame:.
layoutSubviews is ment for laying out subviews.
In fact your code will (should) work if you move all the code fromLayoutSubviews to initWithFrame:. You can then move parts of the code (the laying out part) back.
EDIT: when you move initializing code you will probably also have to add [tblTweets reloadData]; right after tableData = [self getTweets];

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

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!