NSMutableArray Display Null Value in Table View - iphone

- (void)viewDidLoad {
self.detailView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 480) style:UITableViewStylePlain];
self.detailView.dataSource = self;
self.detailView.delegate = self;
self.detailView.multipleTouchEnabled=YES;
[self.view addSubview:self.detailView];
[super viewDidLoad];
self.title = NSLocalizedString(#"Routes", nil);
self.detailArray = [[NSMutableArray alloc] init];
NSString *url = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/directions/json?origin=Chennai&destination=Madurai&sensor=false"];
NSURL *googleRequestURL=[NSURL URLWithString:url];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* data = [NSData dataWithContentsOfURL: googleRequestURL];
NSString *someString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSError* error;
NSMutableDictionary* parsedJson = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *allkeys = [parsedJson allKeys];
for(int i = 0; i < allkeys.count; i++){
if([[allkeys objectAtIndex:i] isEqualToString:#"routes"]){
NSArray *arr = [parsedJson objectForKey:#"routes"];
NSDictionary *dic = [arr objectAtIndex:0];
NSArray *legs = [dic objectForKey:#"legs"];
for(int i = 0; i < legs.count; i++){
NSArray *stepsArr = [[legs objectAtIndex:i] objectForKey:#"steps"];
for (int i = 0; i < stepsArr.count; i++) {
NSLog(#"HTML INSTRUCTION %#", [[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"]);
NSLog(#"############################");
[self.detailArray addObject:[[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"] ];
}
}
}
}
});
}
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger) tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section{
return [self.detailArray 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];
}
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, 5.0f, 300.0f, 30.0f)];
label.text=[NSString stringWithFormat:#"%#",[self.detailArray objectAtIndex:indexPath.row]];
label.numberOfLines = 3;
label.font = [UIFont fontWithName:#"Helvetica" size:(12.0)];
label.lineBreakMode = UILineBreakModeWordWrap;
label.textAlignment = UITextAlignmentLeft;
[cell.contentView addSubview:label];
[label release];
return cell;
}
i want to display the detailArray in the Table View.But it display null values in Table View.But in NSlog it display current values.The detailArray having set of direction values. is any possible to display in TableView.if i give constant value in displayArray its show correctly in TableView. please help me if Any one know.i am waiting for your valuable Answers,Thanks.

UPDATED
After add whole data (values) in after retain it and reload TableView like bellow...
[self.detailArray retain];
[self.detailView reloadData];
i am sure your problem solved... :)

Remove [self.detailView reloadData]; from cellForRowAtIndexPath method. and also remove tableView.delegate = self; in same method.
and remember [super viewDidLoad]; must write at top of viewDidLoad.
Edit
just change your four array as below.
NSArray *legs=(NSArray *)[dic objectForKey:#"legs"];
NSArray *arr = (NSArray *)[parsedJson objectForKey:#"routes"];
NSArray *legs = (NSArray *)[dic objectForKey:#"legs"];
NSArray *stepsArr = (NSArray *)[[legs objectAtIndex:i] objectForKey:#"steps"];

Why are you setting detailView delegate and datasource 2 times in viewDidLoad. Please format the code first then it will be easy for us to describe the problem.
self.detailView.dataSource=self;
self.detailView.delegate=self;
self.detailView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 480) style:UITableViewStylePlain];
self.detailView.dataSource = self;
self.detailView.delegate = self;

Related

NSArray Values are Display after touche in screen in Tableview

- (void)viewDidLoad {
detailView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 330, 380) style:UITableViewStylePlain];
detailView.rowHeight = 55.0f;
detailView.dataSource =self;
detailView.delegate =self;
NSLog(#"finish0");
[self.view addSubview:detailView];
self.title = NSLocalizedString(#"Routes", nil);
self.detailArray = [[NSMutableArray alloc] init];
url = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/directions/json?origin=%#&destination=%f,%f&sensor=false",start1,center.latitude,center.longitude];
NSURL *googleRequestURL=[NSURL URLWithString:url];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* data = [NSData dataWithContentsOfURL: googleRequestURL];
NSError* error;
NSMutableDictionary* parsedJson = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *allkeys = [parsedJson allKeys];
for(int i = 0; i < allkeys.count; i++){
if([[allkeys objectAtIndex:i] isEqualToString:#"routes"]){
NSArray *arr = [parsedJson objectForKey:#"routes"];
NSDictionary *dic = [arr objectAtIndex:0];
legs = [dic objectForKey:#"legs"];
for(int i = 0; i < legs.count; i++){
NSArray *stepsArr = [[legs objectAtIndex:i] objectForKey:#"steps"];
for (int i = 0; i < stepsArr.count; i++) {
[self.detailArray addObject:[[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"] ];
string = [self.detailArray componentsJoinedByString:#","];
NSLog(#"string%#",string);
[self stringByStrippingHTML];
self.detail=[string componentsSeparatedByString:#","];
[self.detail retain];
[detailView reloadData];
}}}}
});
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger) tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section{
return [detail count];
NSLog(#"table2");
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"table4");
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.selectionStyle = UITableViewCellSelectionStyleNone;
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(5.0f, 0.0f, 300.0f, 60.0f)];
label.text=[NSString stringWithFormat:#"%#",[detail objectAtIndex:indexPath.row]];
label.numberOfLines = 3;
label.font = [UIFont fontWithName:#"Helvetica" size:(12.0)];
label.lineBreakMode = UILineBreakModeWordWrap;
label.textAlignment = UITextAlignmentLeft;
[cell.contentView addSubview:label];
[label release];
return cell;
}
-(NSString *) stringByStrippingHTML {
NSRange r;
while ((r = [string rangeOfString:#"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
string = [string stringByReplacingCharactersInRange:r withString:#""];
return string;
}
In The coding the values of self.detail(array) display after touches the screen in TableView.i need to display the values immediately when i enter the TableView. please any one help if you know. and tell me why the values of NSArray display only after touch or scroll the tableview.
try this
[self.detailView performSelectorOnMainThread:#selector(reloadData) withObject:nil waitUntilDone:NO];
instead of [detailView reloadData];
You need to reload the table view after you have finished downloading the data and populating your array with the result. That is
url = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/directions/json?origin=%#&destination=%f,%f&sensor=false",start1,center.latitude,center.longitude];
NSURL *googleRequestURL=[NSURL URLWithString:url];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* data = [NSData dataWithContentsOfURL: googleRequestURL];
NSError* error;
NSMutableDictionary* parsedJson = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *allkeys = [parsedJson allKeys];
for(int i = 0; i < allkeys.count; i++){
if([[allkeys objectAtIndex:i] isEqualToString:#"routes"]){
NSArray *arr = [parsedJson objectForKey:#"routes"];
NSDictionary *dic = [arr objectAtIndex:0];
legs = [dic objectForKey:#"legs"];
for(int i = 0; i < legs.count; i++){
NSArray *stepsArr = [[legs objectAtIndex:i] objectForKey:#"steps"];
for (int i = 0; i < stepsArr.count; i++) {
[self.detailArray addObject:[[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"] ];
string = [self.detailArray componentsJoinedByString:#","];
NSLog(#"string%#",string);
[self stringByStrippingHTML];
self.detail=[string componentsSeparatedByString:#","];
[self.detail retain];
}}}}
[detailView reloadData];
}
Also to explain why the table loads after you scroll the TableView; When you scroll in the table view the delegate method -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath (among with others) will be called to update the tableview.

Want to display the array values in the table

Table View:
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger) tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section{
return [self.detailArray 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];
}
tableView.delegate = self;
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10.0f, 5.0f, 300.0f, 30.0f)];
label.text=[NSString stringWithFormat:#"%#",[self.detailArray objectAtIndex:indexPath.row]];
label.numberOfLines = 3;
label.font = [UIFont fontWithName:#"Helvetica" size:(12.0)];
label.lineBreakMode = UILineBreakModeWordWrap;
label.textAlignment = UITextAlignmentLeft;
[cell.contentView addSubview:label];
[label release];
[self.myTableView reloadData];
return cell;
}
I want to store the detail (array value) in the tableView.I used both method numberOfRowsInSection and cellForRowAtIndexPath but the table display null. How can I display?
Make property for NSMutable array in .h
#property (nonatomic,retain) NSMutableArray *detailArray;
and synthesize it in .m
#synthesize detailArray=_detailArray;
and change this line
NSMutableArray *detail=[[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"] ;
to
_detailArray=[[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"] ;
then use _detailArray for displaying table data.
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section {
return [_detailArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// _detailArray objects for date population.
}
Your Code :
NSString *url = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/directions/json?origin=%#&destination=%f,%f&sensor=false",startPoint,midannotation.coordinate.latitude,midannotation.coordinate.longitude];
NSURL *googleRequestURL=[NSURL URLWithString:url];
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL: googleRequestURL];
NSString *someString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
// NSLog(#"data:%#",someString);
NSError* error;
NSMutableDictionary* parsedJson = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *allkeys = [parsedJson allKeys];
for(int i = 0; i < allkeys.count; i++){
if([[allkeys objectAtIndex:i] isEqualToString:#"routes"]){
arr = [parsedJson objectForKey:#"routes"];
dic = [arr objectAtIndex:0];
// NSLog(#"ALL KEYS FROM ROUTE: %#", [dic allKeys]);
legs = [dic objectForKey:#"legs"];
// NSLog(#"legs array count %d", legs.count);
for(int i = 0; i < legs.count; i++){
stepsArr = [[legs objectAtIndex:i] objectForKey:#"steps"];
for (int i = 0; i < stepsArr.count; i++) {
NSLog(#"HTML INSTRUCTION %#", [[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"]);
NSLog(#"############################");
NSMutableArray *detail=[[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"] ;
}
}
}
}
});
first you go to your .h file -->
#property (nonatomic, strong) NSMutableArray * detailsArray;
In .m file -->
#synthesize detailsArray;
replace this code
NSMutableArray *detail=[[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"] ;
by this -->
self.detailsArray = [[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"];
# using table datasource methods
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section {
return [self.detailsArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.titleLabel.text = [self.detailsArray objectAtIndex: indexPath.row ];
return cell;
}
}
//Note Please set the delegate method of table , if you write the code programmatically means tableView.delgate = self;
Use this :
self.detaisArray = [[NSMutableArray alloc] init];
// Do any additional setup after loading the view, typically from a nib.
NSString *url = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/directions/json?origin=%#&destination=%f,%f&sensor=false",startPoint,midannotation.coordinate.latitude,midannotation.coordinate.longitude];
NSURL *googleRequestURL=[NSURL URLWithString:url];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* data = [NSData dataWithContentsOfURL: googleRequestURL];
NSString *someString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
// NSLog(#"data:%#",someString);
NSError* error;
NSMutableDictionary* parsedJson = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *allkeys = [parsedJson allKeys];
for(int i = 0; i < allkeys.count; i++){
if([[allkeys objectAtIndex:i] isEqualToString:#"routes"]){
NSArray *arr = [parsedJson objectForKey:#"routes"];
NSDictionary *dic = [arr objectAtIndex:0];
// NSLog(#"ALL KEYS FROM ROUTE: %#", [dic allKeys]);
NSArray *legs = [dic objectForKey:#"legs"];
// NSLog(#"legs array count %d", legs.count);
for(int i = 0; i < legs.count; i++){
NSArray *stepsArr = [[legs objectAtIndex:i] objectForKey:#"steps"];
for (int i = 0; i < stepsArr.count; i++) {
NSLog(#"HTML INSTRUCTION %#", [[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"]);
NSLog(#"############################");
[self.detaisArray addObject:[[stepsArr objectAtIndex:i] objectForKey:#"html_instructions"] ];
if(i == legs.count-1){
self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 20, 320, 400) style:UITableViewStylePlain];
self.myTableView.delegate = self;
self.myTableView.dataSource = self;
[self.view addSubview:self.myTableView];
}
}
}
}
}
});
first checked you connect your tableview delegate set self...
second checked youn row count pr detailarray cont in numberOfRowsInSection its may b zero
1st Declare Your Array in .h
like this
#property(strong,nonatomic)NSMutableArray * name;
And intialize into .m Init() method
name=[NSMutableArray alloc]initWithObjects:#"a",#"b", nil];
// TableView Delegate Method To Display Array Data into Tableview.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return name.count; //Give Your Array Name Here.
}
- (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.text=[NSString stringWithFormat:#"%#",[name objectAtIndex:indexPath.row]];
return cell;
}
Try this code.

IPhone - Images making scrolling and other functionality to crash

Everytime i load images in a tableview and try to scroll the table view i get a crash in my simulator but no errors are showing. Could this be that there is to much memory being used.
Below is the code for 1 out the three views:
#import "ResultViewController.h"
#import "JobAddSiteViewController.h"
#import "SpecificAddViewController.h"
#import "JobAddSiteAppDelegate.h"
#import "JSONKit.h"
#implementation ResultViewController
#synthesize listData;
#synthesize listLocation;
#synthesize listPostDate;
#synthesize listLogo;
#synthesize listDescription;
#synthesize uiTableView;
#synthesize buttonPrev;
#synthesize buttonNext;
NSInteger *countPage = 1;
NSMutableArray *tempArray;
NSMutableArray *tempArray2;
NSMutableArray *tempArray3;
NSMutableArray *tempArray4;
NSMutableArray *tempArray5;
-(IBAction)done{
JobAddSiteViewController *second = [[JobAddSiteViewController alloc]initWithNibName:nil bundle:nil];
[self presentModalViewController:second animated:YES];
[second release];
}
-(void)loadData{
NSString *strURL2 = [NSString stringWithFormat:#"http://www.bestitjobs.co.uk/totaljobs.php", ""];
NSData *nsData2 = [NSData dataWithContentsOfURL:[NSURL URLWithString: strURL2]];
NSString *dataResult = [[NSString alloc] initWithData:nsData2 encoding:NSUTF8StringEncoding];
tempArray = [[NSMutableArray alloc] init];
tempArray2 = [[NSMutableArray alloc] init];
tempArray3 = [[NSMutableArray alloc] init];
tempArray4 = [[NSMutableArray alloc] init];
tempArray5 = [[NSMutableArray alloc] init];
NSString *strURL = [NSString stringWithFormat:#"http://www.bestitjobs.co.uk/appresults3.php?pg=%d", countPage];
NSData *nsData = [NSData dataWithContentsOfURL:[NSURL URLWithString: strURL]];
NSDictionary *listDictionary = [nsData objectFromJSONData];
NSArray* people =[listDictionary objectForKey:#"jobs"];
for (NSDictionary *person in people) {
NSString *str = [NSString stringWithFormat:#"%#", [person valueForKey:#"position"]];
NSString *str2 = [NSString stringWithFormat:#"%#", [person valueForKey:#"subcounty"]];
NSString *str3 = [NSString stringWithFormat:#"%#", [person valueForKey:#"postdate"]];
NSString *str4 = [NSString stringWithFormat:#"%#", [person valueForKey:#"logo"]];
NSString *str5 = [NSString stringWithFormat:#"%#", [person valueForKey:#"description"]];
if(![str isEqualToString:#"<null>"])
{
NSString *position = [person objectForKey:#"position"];
[tempArray addObject: position];
if(![str2 isEqualToString:#"<null>"])
{
NSString *subcounty = [person objectForKey:#"subcounty"];
[tempArray2 addObject: subcounty];
}
else{
[tempArray2 addObject: #"-"];
}
if(![str3 isEqualToString:#"<null>"])
{
NSString *postDate = [person objectForKey:#"postdate"];
[tempArray3 addObject: postDate];
}
else{
[tempArray3 addObject: #"-"];
}
if(![str4 isEqualToString:#"<null>"])
{
NSString *logo = [person objectForKey:#"logo"];
[tempArray4 addObject: [NSString stringWithFormat:#"http://www.bestitjobs.co.uk/employers/logo/Files/%#", logo]];
}
else{
[tempArray4 addObject: [NSString stringWithFormat:#"http://www.bestitjobs.co.uk/employers/logo/Files/%#", "noimage.gif"]];
}
if(![str5 isEqualToString:#"<null>"])
{
NSString *description = [person objectForKey:#"description"];
[tempArray5 addObject: description];
}
else{
[tempArray5 addObject: #"-"];
}
}
}
if (countPage == 1) {
[self.buttonPrev setEnabled:FALSE];
}
else {
[self.buttonPrev setEnabled:TRUE];
}
NSInteger val = [dataResult intValue];
NSInteger pageEnd = val/10;
if (countPage < pageEnd) {
[self.buttonNext setEnabled:TRUE];
}
else {
[self.buttonNext setEnabled:FALSE];
}
//NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:#"iPhone", #"iPod",#"iPad",nil];
self.listData = tempArray;
self.listLocation = tempArray2;
self.listPostDate = tempArray3;
self.listLogo = tempArray4;
self.listDescription = tempArray5;
[self.listData release];
[self.listLocation release];
[self.listPostDate release];
[self.listLogo release];
[self.listDescription release];
tempArray = nil;
tempArray2 = nil;
tempArray3 = nil;
tempArray4 = nil;
tempArray5 = nil;
}
- (void)viewDidLoad {
[self loadData];
[super viewDidLoad];
}
- (void)dealloc {
[tempArray dealloc];
[tempArray2 dealloc];
[tempArray3 dealloc];
[tempArray4 dealloc];
[tempArray5 dealloc];
[self.listData dealloc];
[self.listLocation dealloc];
[self.listPostDate dealloc];
[self.listLogo dealloc];
[self.listDescription dealloc];
[super dealloc];
}
#pragma mark -
#pragma mark Table View Data Source Methods
- (IBAction)prev{
countPage = countPage - 1;
[self.listData removeAllObjects];
[self.listLocation removeAllObjects];
[self.listPostDate removeAllObjects];
[self.listLogo removeAllObjects];
//NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:#"1", #"2",#"3",nil];
//self.listData = array;
[self loadData];
[self.uiTableView reloadData];
}
- (IBAction)next{
countPage = countPage + 1;
[self.listData removeAllObjects];
[self.listLocation removeAllObjects];
[self.listPostDate removeAllObjects];
[self.listLogo removeAllObjects];
//NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:#"1", #"2",#"3",nil];
//self.listData = array;
[self loadData];
[self.uiTableView reloadData];
}
- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath {
JobAddSiteAppDelegate *ja = (JobAddSiteAppDelegate *)[[UIApplication sharedApplication] delegate];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
for (UIView *view in cell.contentView.subviews){
if ([view isKindOfClass:[UILabel class]]){
UILabel *label = (UILabel *)view;
if (label.tag == 1) {
ja.jobText = label.text;
}
if (label.tag == 2) {
ja.locationText = label.text;
}
if (label.tag == 3) {
ja.dateText = label.text;
}
if (label.tag == 4) {
}
if (label.tag == 5) {
ja.specificText = label.text;
}
}
if ([view isKindOfClass:[UIImageView class]]){
UIImageView *image = (UIImageView *)view;
if (image.tag = 4){
ja.logoText = image.image;
}
}
}
SpecificAddViewController *second = [[SpecificAddViewController alloc]initWithNibName:nil bundle:nil];
[self presentModalViewController:second animated:YES];
[second release];
}
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
return [self.listData count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath
*)indexPath
{
if (indexPath.section == 1 && indexPath.row == 1) {
return 65;
}
return 65;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *SimpleTableIdentifier = #"SimpleTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SimpleTableIdentifier];
UILabel *labelMain;
UILabel *labelLocation;
UILabel *labelDate;
UIImageView *image;
UILabel *ref;
if (cell == nil) {
cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableIdentifier] autorelease];
image = [[[UIImageView alloc] initWithFrame:CGRectMake(0,3,80,62)] autorelease];
image.tag = 4;
[cell.contentView addSubview:image];
labelMain = [[[UILabel alloc] initWithFrame:CGRectMake(90,3,200,20)] autorelease];
labelMain.tag = 1;
labelMain.font = [UIFont systemFontOfSize:14.0];
[cell.contentView addSubview:labelMain];
labelLocation = [[[UILabel alloc] initWithFrame:CGRectMake(90,20,200,20)] autorelease];
labelLocation.tag = 2;
labelLocation.font = [UIFont systemFontOfSize:12.0];
labelLocation.textColor = [UIColor darkGrayColor];
[cell.contentView addSubview:labelLocation];
labelDate = [[[UILabel alloc] initWithFrame:CGRectMake(90,40,200,20)] autorelease];
labelDate.tag = 3;
labelDate.font = [UIFont systemFontOfSize:12.0];
labelDate.textColor = [UIColor darkGrayColor];
[cell.contentView addSubview:labelDate];
ref = [[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 0)] autorelease];
ref.tag = 5;
[cell.contentView addSubview:ref];
}
[(UILabel *)[cell.contentView viewWithTag:1] setText:[self.listData objectAtIndex:indexPath.row]];
[(UILabel *)[cell.contentView viewWithTag:2] setText:[self.listLocation objectAtIndex:indexPath.row]];
[(UILabel *)[cell.contentView viewWithTag:3] setText:[self.listPostDate objectAtIndex:indexPath.row]];
[(UILabel *)[cell.contentView viewWithTag:5] setText:[self.listDescription objectAtIndex:indexPath.row]];
NSString *imagePath = [self.listLogo objectAtIndex:indexPath.row];
image.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imagePath]]];
return cell;
}
#end
The call
image.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imagePath]]];
will block the execution thread and being indeterminately long in terms of network use this is a bad thing. Each of your cells needs to wait to the image to load.
Check out "lazy loading of tableView cells" as a research topic.
Instead you should give the URL to the cell and tell it to load the image off the main thread.
as in
[cell loadImageAtURL:someURL];
and within a UITableViewCell subclass implementation
-(void)loadImageAtURL:(NSURL *)aurl
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
NSData *data = [NSData dataWithContentsOfURL:aurl];
if (data) {
UIImage *image = [UIImage imageWithData:data];
//must update UI on main queue
dispatch_async(dispatch_get_main_queue() ,^{
self.cellImageView = image;
}
}
});
}
Theres also a ton of Obj-C image loaders . EGOCache is my go to library but have a look round.
In summary the cell needs to own the image load process not the tableview because theres no guarantee that the cell will not be reused before the image loads and displays.
NSInteger is a primitive type, which means it can be stored locally on the stack. You don't need to use a pointer to access it. The way you are using it i think is a problem, getting the pointer value instead of the actual value of the primitive type.
I think this is what you want for the declaration/initialization of countPage:
NSInteger countPage = 1;

UITableview doubts

i am having an application which can share Notes to evernote,it works fine i can upload and download my Note to Evernote within the app,i have a Note title and Note subject,i uploaded the Notes to evernote viz UITableview controller.The Textlabel.text is the title for the note and detailtextlabel.text is the note subject.i only get the Notesubject correctly means ,if i have two notes in tableview with title,like this formate 1) title :firstitle ,notesubject :firstNotessubject 2)title :secondtitle ,notesubject :secondNotessubject,,then i press the upload button it uploads the notes to evernote,but the title remains firstitle only with notes,like this formate 1) title :firstitle ,notesubject :firstNotessubject 2)title :firsttitle ,notesubject :secondNotessubject.my code for uplode button is
-(IBAction)sendNoteEvernote:(id)sender{
NSMutableString *strtitle = [[NSMutableString alloc] initWithString:#""];
for (int t = 0; t<[appDelegate.indexArray count]; t++) {
NSString * aStringtitle = [[NSString alloc] initWithString:[appDelegate.indexArray objectAtIndex:t]] ;
note.title =aStringtitle;
}
NSMutableString *str = [[NSMutableString alloc] initWithString:#"NOTES:"];
for (int i = 0; i<[appDelegate.notesArray count]; i++) {
NSString * aString = [[NSString alloc] initWithString:[appDelegate.notesArray objectAtIndex:i]] ;
NSString * ENML= [NSString stringWithFormat:#"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">\n<en-note>%#",aString];
ENML = [NSString stringWithFormat:#"%#%#", ENML, #"</en-note>"];
NSLog(#"%#", ENML);
// Adding the content & resources to the note
[note setContent:ENML];
// [note setTitle:aStringtitle];
// [note setResources:resources];
// Saving the note on the Evernote servers
// Simple error management
#try {
[[eversingleton sharedInstance] createNote:note];
_acteverbackup.hidden = YES;
_actimageeverbackup.hidden =YES;
}
#catch (EDAMUserException * e) {
_acteverbackup.hidden = YES;
_actimageeverbackup.hidden =YES;
NSString * errorMessage = [NSString stringWithFormat:#"Error saving note: error code %i", [e errorCode]];
proAlertView *alert = [[proAlertView alloc]initWithTitle:#"Evernote" message:errorMessage delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil];
[alert setBackgroundColor:[UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1.0] withStrokeColor:[UIColor colorWithHue:0.0 saturation:0.0 brightness:0.0 alpha:1.0]];
[alert show];
[alert release]; return;
}
in the above code appdelegate.indexarray is the title and appdelegate.notearray is the Subject..my UItableview code look like this.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return[appDelegate.notesArray count];
}
/*-(UITableViewCellAccessoryType)tableView:(UITableView *)tableView accessoryTypesForRowWithIndexPath:(NSIndexPath *)indexPath
{
return UITableViewCellAccessoryCheckmark;
}*/
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSUInteger row = [indexPath row];
NSString *CellIdentifier;
CellIdentifier=[NSString stringWithFormat:#"cell %d",indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
cell.detailTextLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.detailTextLabel.numberOfLines = 0;
UIImageView* img = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#"bgCELL3#2X-1"]];
[cell setBackgroundView:img];
[img release];
count++;
}
NSMutableString *strr=[[NSMutableString alloc]initWithString:[appDelegate.indexArray objectAtIndex:indexPath.section]];
cell.textLabel.text =strr ;
cell.textLabel.text = [appDelegate.indexArray objectAtIndex:row];
cell.textLabel.font = [UIFont fontWithName:#"Georgia" size:14.0];
cell.textLabel.textColor = [UIColor brownColor];
//NSMutableString *notes=[[NSMutableString alloc]initWithString:[appDelegate.notesArray objectAtIndex:row]];
//cell.detailTextLabel.text =notes;
cell.detailTextLabel.font = [UIFont fontWithName:#"Georgia" size:14.0];
cell.detailTextLabel.textColor = [UIColor darkGrayColor];
cell.detailTextLabel.text = [appDelegate.notesArray objectAtIndex:row];
//textView.text=notes;
//[notes release];
cell.backgroundColor=[UIColor clearColor];
cell.accessoryType = UITableViewCellAccessoryNone;
return cell;
}
whats the error in my code,please help me to do this.
thanks in advance
Try changing the line:
NSMutableString *strr = [[NSMutableString alloc] initWithString:[appDelegate.indexArray objectAtIndex:indexPath.section]];
to:
NSMutableString *strr = [[NSMutableString alloc] initWithString:[appDelegate.indexArray objectAtIndex: row]];
Also get rid of the:
NSUInteger row = [indexPath row];
NSString *CellIdentifier;
CellIdentifier = [NSString stringWithFormat:#"cell %d",indexPath.row];
simply use:
CellIdentifier = #"noteCellIdentifier";
This doesn't have anything to do with your question but it's what cell reusing is all about.
EDIT:
This part of code also looks suspitious:
for (int t = 0; t<[appDelegate.indexArray count]; t++) {
NSString * aStringtitle = [[NSString alloc] initWithString:[appDelegate.indexArray objectAtIndex:t]] ;
note.title =aStringtitle;
}
It's not clear what you want to do but you'd probably want to move this to:
for (int i = 0; i<[appDelegate.notesArray count]; i++) {
NSString * aStringtitle = [[NSString alloc] initWithString:[appDelegate.indexArray objectAtIndex:i]]; //note: t changed to i
note.title =aStringtitle;
NSString * aString = [[NSString alloc] initWithString:[appDelegate.notesArray objectAtIndex:i]];
NSString * ENML= [NSString stringWithFormat:#"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\">\n<en-note>%#",aString];
ENML = [NSString stringWithFormat:#"%#%#", ENML, #"</en-note>"];
NSLog(#"%#", ENML);
//....

Application crashes when scrolling UITableView to reveal bottom rows

I have an application which displays data in a UITableView. However, it crashes when i try to reveal the bottom rows. Hope someone can shed some light on why this is happening.
-(void)viewDidLoad {
NSLog(#"myString is :%#", myString);
int processID = [myString intValue];
//NSLog(#"transferredArray is %#", transferredArray);
task = [[NSTask alloc] init];
[task setLaunchPath: #"/bin/ps"];
arguments = [NSArray arrayWithObjects: #"aux", [NSString stringWithFormat:#"%i", processID],nil];
[task setArguments: arguments];
NSPipe *pipe;
pipe = [NSPipe pipe];
[task setStandardOutput:pipe];
NSFileHandle *file;
file = [pipe fileHandleForReading];
[task launch];
NSData *data;
data = [file readDataToEndOfFile];
NSString *string;
string = [[NSString alloc] initWithData: data
encoding: NSUTF8StringEncoding];
NSLog(#"ps aux output :%#",string);
NSArray *lines= [string componentsSeparatedByString:#"\n"];
NSString *lastline = [lines objectAtIndex:[lines count]-2];
// NSLog(#"%#",lastline);
lines2= [lastline componentsSeparatedByString:#" "];
NSLog(#"%#",lines2);
for (int i=0; i<[lines2 count]; i++) {
if([[lines2 objectAtIndex:i] isEqualToString:#""]){
[lines2 removeObjectAtIndex:i];
}
}
for (int i=0; i<[lines2 count]; i++) {
if([[lines2 objectAtIndex:i] isEqualToString:#""]){
[lines2 removeObjectAtIndex:i];
}
}
NSLog(#"lines2 after for loops is %#", lines2);
NSLog(#"Lines 2 is%#",lines2);
// NSLog(#"Status is %#",[lines2 objectAtIndex:7]);
self.title = #"Process Info";
label = [[NSMutableArray alloc]init];
[label addObject:#"User:"];
[label addObject:#"Process ID:"];
[label addObject:#"CPU(%):"];
[label addObject:#"MEM(%):"];
[label addObject:#"VSZ"];
[label addObject:#"RSS"];
[label addObject:#"TT"];
[label addObject:#"STAT:"];
[label addObject:#"Time Started:"];
[label addObject:#"Time Elapsed:"];
[label addObject:#"Command:"];
[super viewDidLoad];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UILabel *label2;
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]autorelease];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
cell.textColor = [UIColor colorWithRed:154.0/255.0 green:14.0/255.0 blue:2.0/255.0 alpha:1];
cell.font = [UIFont systemFontOfSize:16.0];
label2 = [[[UILabel alloc] initWithFrame:CGRectMake(120.0, 0, 240.0,
tableView.rowHeight)]autorelease];
label2.font = [UIFont systemFontOfSize:16.0];
NSString *cellValue1 = [lines2 objectAtIndex:indexPath.row];
label2.text = cellValue1;
label2.textAlignment = UITextAlignmentLeft;
label2.textColor = [UIColor blackColor];
label2.autoresizingMask = UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:label2];
}
NSString *cellValue = [label objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
return cell;
}
- (void)viewWillDisappear:(BOOL)animated
{
[task terminate];
[task release];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [lines2 count];
}
- (void)dealloc
{
//[transferredArray release];
//[myString release];
//[arguments release];
//[ResultStringID release];
//[values release];
//[label release];
[super dealloc];
}
Note : I commented out all the [release]'s in the dealloc method to prevent any other EXEC_BAD_ACCESS errors, although the current error I am encountering is EXEC_BAD_ACCESS
Couple of things spring to mind:
You are trying to remove objects from an NSArray (lines2). This is not possible.
Your table view determines its number of rows from the count of lines2, but you attempt to access the labels array with the indexPath.row - if there are more entries in lines2 than labels this will cause a crash.
You never change the value in your label2 label which will look very odd when scrolling. You should give this a tag and then change the content in the same place as you set cell.textLabel.text
lines2 is autoreleased so may not be around when you come to access it in cellForRowAtIndexPath
put [lines2 retain] as last statement in viewDidLoad method it will work fine.