XCode, table view cellForRowAtIndexPath - xcode

I know there is a simple solution to this but I can't seem to be able to tell :/
cell.textLabel.text = [BooksBorrowed objectAtIndex:0];
I have that in my cellForRowAtIndexPath method, bookName is a string.
It crashes and leaves no error in log. I dont know what I am doing wrong.
bookName is a string that i get from JSON Parsing and has content.
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
NSLog(#"Book Name is %#", BooksBorrowed[0]);
cell.textLabel.text = [BooksBorrowed objectAtIndex:0];
return cell;
}
This is how I get the BooksBorrowed array:
- (void)updateMyBooks
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Fetch data on a background thread:
NSString *authFormatString =
#"http://localhost:8888/Jineel_lib/bookBorrowed.php?uid=%d";
NSString *urlString = [NSString stringWithFormat:authFormatString, 1];
NSURL *url = [NSURL URLWithString:urlString];
NSString *contents = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
response1 = [contents JSONValue];
if (contents) {
NSMutableArray *newBooksBorrowed = [NSMutableArray array];
// ... Parse JSON response and add objects to newBooksBorrowed ...
BookName = [[NSString alloc]init];
DateBorrowed = [[NSString alloc]init];
BookID = [[NSString alloc]init];
BookExtended = [[NSString alloc]init];
BookReturned = [[NSString alloc]init];
BookName = [response1 valueForKey:#"BookName"];
BookID = [response1 valueForKey:#"BookID"];
DateBorrowed = [response1 valueForKey:#"DateBorrowed"];
BookExtended = [response1 valueForKey:#"Extended"];
BookReturned = [response1 valueForKey:#"Returned"];
NSLog(#"Book Name is %#", BookName);
[newBooksBorrowed addObject:BookName];
dispatch_sync(dispatch_get_main_queue(), ^{
// Update data source array and reload table view.
BooksBorrowed = newBooksBorrowed;
[self.tableView reloadData];
});
}
});
}

Are you sure bookName is a valid NSString? I would break at that line of code and type
po bookName
in the debugger to see if what you are assigning to bookName is in fact a valid NSString.
Oh, and make sure you returning a valid UITableViewCell at the end of that method, or else it is guaranteed your code will break.

Replace this code BooksBorrowed = newBooksBorrowed; with this in your function
BooksBorrowed = [[NSString alloc] initWithArray:newBooksBorrowed];
Hope it helps. Happy coding..
Thanks.

The solution to my questions was :
I had to change the part where I add my data into the table to :
NSString *string = [[NSString alloc] initWithFormat:#"%#",[BooksBorrowed objectAtIndex:indexPath.row]];
This is because a table view tends to not take things of element 0. Also I took out newBooksBorrowed and it works with just the BooksBorrowed array. :) Thank you everyone for helping me resolve it.

Related

Loading Images into a tableview cell, according to object loaded from NSUserDefaults

I have a tableview populated by objects loaded from NSUserDefaults.
Specifically - when a user presses a button in one view controller, a string is loaded into NSUserDefaults, which is then loaded into an array, which finally populates a table view.
I am wondering how I can load an image in each tableview cell, dependent on what string is loaded from NSUserDefaults?
I don't want to save images IN NSUserDefaults, as I am aware this is not a good idea.
What can I do?
Thank you for your time (and helping a novice out)!
Update 19FEB13
The Strings I am loading into NSUserDefaults are the names of objects, for example "ARCX".
At the moment I have tried a variety of pieces of code, but I am at the point where I seem to have a misunderstanding/lack of knowledge (or both).
UITableViewCell *XCell = [tableView cellForRowAtIndexPath:IndexPath];
NSString *content = Xcell.textLabel.text;
if ([content isEqualToString:#"ARCX"]) [UIImage *Image = [UIImage imageNamed #"ARCX.png"]];
Obviously I'm getting errors from this code.
I hope you can help!
Update 20FEB13
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *string = [myOBJArray objectAtIndex:indexPath.row];
static NSString *CellIdentifier = #"XCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
UIView *cellbackground = [[UIView alloc] initWithFrame:CGRectZero];
cellbackground.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"MSP cell bg MK2.png"]];
cell. backgroundView = cellbackground;
}
cell.textLabel.textColor = [UIColor yellowColor ];
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:24.0];
cell.textLabel.text = string;
UITableViewCell *XCell = [tableView cellForRowAtIndexPath:indexPath];
NSString *content = XCell.textLabel.text;
if ([content isEqualToString:#"ARCX"]) [UIImage *Image = [UIImage imageNamed: #"ARCX.png" ]];
cell.imageView.image = Image;
return cell;
}
I did have the code I initially posted in the CellForRowAtIndexPath, but I know I am missing something in the implementation (obviously as it doesn't work!).
Thanks for your time!
Update 19Feb13
I This is my current CellForRowAtIndexPath. No errors, but yet no images in my cells. What am I missing?
Have I got to add an image view? I am currently using a 'basic' cell, not a custom one.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *string = [myObjArray objectAtIndex:indexPath.row];
static NSString *CellIdentifier = #"MSCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
UIView *cellbackground = [[UIView alloc] initWithFrame:CGRectZero];
cellbackground.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"MSP cell bg MK2.png"]];
cell. backgroundView = cellbackground;
}
cell.textLabel.textColor = [UIColor blackColor ];
cell.textLabel.font = [UIFont fontWithName:#"Helvetica" size:24.0];
cell.textLabel.text = string;
if ([string isEqualToString:#"ARCX"])
cell.imageView.image = [UIImage imageNamed: #"ARCX.png"];
else if ([string isEqualToString:#"WPX"])
cell.imageView.image = [UIImage imageNamed:#"WPX.png"];
return cell;
}
Thanks for your time!
UITableViewCell *XCell = [tableView cellForRowAtIndexPath:indexPath];
NSString *content = XCell.textLabel.text;
Please remove this piece of code, as it will call cellForRowAtIndexPath again and again.
You already have the image name as string
NSString *string = [myOBJArray objectAtIndex:indexPath.row];
So change the code like below.
if ([string isEqualToString:#"ARCX"])
UIImage *Image = [UIImage imageNamed: #"ARCX.png"];
cell.imageView.image = Image;

TWRequest from a dictionary in a tableView Cell

I am trying to propagate a table view with a custom cell with the results of a TWRequest with no luck. I am trying to store the tweets in a dictionary object then calling an ObjectAtKey request and putting into a string. Here is my code - any help would be appreciated. Thanks -
-(void)fetchTweets
{
// Do a simple search, using the Twitter API
TWRequest *request = [[TWRequest alloc] initWithURL:[NSURL URLWithString:
#"http://search.twitter.com/search.json?q=iOS%205&rpp=5&with_twitter_user_id=true&result_type=recent"]
parameters:nil requestMethod:TWRequestMethodGET];
// Notice this is a block, it is the handler to process the response
[request 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 *dict = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
NSLog(#"Twitter response: %#", dict);
}
else
NSLog(#"Twitter error, HTTP response: %i", [urlResponse statusCode]);
}];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return tweets.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"cell";
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSString *tweetText = [dict objectForKey:#"text"];
NSArray *tweetComponents = [tweetText componentsSeparatedByString:#":"];
cell.Header.text = [tweetComponents objectAtIndex:0];
cell.Details.text = [tweetComponents objectAtIndex:1];
cell.Date.text = [tweetComponents objectAtIndex:2];
return cell;
}
You will need to create an NSMutableArray of the tweets from the Twitter response.
Each tweet being a separate object.
NSMutableArray *resultArray = [[NSMutableArray] alloc] init];
for (NSDictionary *tweet in dict)
{
[resultArray addObject:tweet];
}
Then in cellForRowAtIndexPath retrieve the object based on the row of the table, something like
TweetResult *tweetResult [resultArray objectAtIndex:[indexPath row]];

Custom cells - how can I separate out tweets into componentsseparatedbyString

I have a custom cell in a tableview. All connections are made. I am conducting a Twitter search. The results of this propagate a custom cell in a tableView. I would like to separate the individual tweets out into an array using componentsseparatedbystring so that I can assign these to 4 labels in my custom cell. Any help would be greatly appreciated. Here is my code.
- (void)fetchTweets
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* data = [NSData dataWithContentsOfURL:
[NSURL URLWithString: #"https://api.twitter.com/1/statuses/public_timeline.json"]];
NSError* error;
tweets = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
});
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return tweets.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"TweetCell";
customCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
// added this bit in
cell = [[customCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// THIS IS THE BIT I'M STRUGGLING WITH
// I'M GUESSING THAT THIS LINE SEPARATES THE TWEETS INTO SINGLE TWEETS?
NSDictionary *tweet = [tweets objectAtIndex:indexPath.row];
// I THEN CREATE AN ARRAY TO HOLD MY COMPONENTS OF THE TWEET SO THAT I CAN SPLIT FOR MY LABELS
NSArray *arrayForCustomCell = [[NSArray alloc] init];
arrayForCustomCell = [tweet componentsSeparatedByString:#":"];
return cell;
}
You have already parsed the results in your async call. Now, you have an array of 'tweet' dictionaries and you can grab any value like this:
NSDictionary *tweet = [tweets objectAtIndex:indexPath.row];
NSString *tweetText = [tweet valueForKey:#"text"];
NSString *tweetCountry = [tweet valueForKeyPath:#"place.country"] //Nested property
and then you just set your UILabels. You get the idea...

My tableview crash when i scroll

I don't undestand... i succeed in populate my table view but when i scroll it crash without message..
i create my tabQuestion with a NSMutablearray and then add this in my delegate : cellForRowAtIndexPath
NSDictionary *question = [self.tabQuestion objectAtIndex:indexPath.row];
[cell setAccessoryType: UITableViewCellAccessoryDisclosureIndicator];
cell.textLabel.text = [NSString stringWithFormat:#"%#", [question objectForKey:#"question"]];
cell.detailTextLabel.text = [NSString stringWithFormat:#"%#", [question objectForKey:#"reponse"]];
if ([[question objectForKey:#"bOk"] isEqualToString:#"1"]) {
cell.imageView.image = [UIImage imageNamed:#"ok.png"];
}
else
{
cell.imageView.image = [UIImage imageNamed:#"ok.png"];
}
[question release];
return cell;
You shouldn't release objects that were returned by method objectAtIndex: of NSArray. It happens very rare.
Try to remove first of all line: [question release];
Then check if your self.tabQuestion contains needful amount of objects.

iPhone UITableViewCell slow performance

I just wrote a small application that read from a site feed and display in UITableViewCell. I am using custom view cell and my UITableView is screwed in scrolling like it is not very smooth in scrolling upside down. Any idea? Here's the code for my UITableViewCell,
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"CustomCell";
CustomCell *cell = (CustomCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
// cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"CustomCell" owner:nil options:nil];
for(id currentObject in topLevelObjects) {
if([currentObject isKindOfClass:[UITableViewCell class]]) {
cell = (CustomCell *) currentObject;
break;
}
}
}
//MiceAppDelegate *AppDelegate = (MiceAppDelegate *)[[UIApplication sharedApplication] delegate];
if(dataArray != nil) {
//
//NSArray *promoArray = (NSArray *) promotions;
NSDictionary *datadict = [self.dataArray objectAtIndex:indexPath.row];
NSString *url = [datadict objectForKey:#"imageUrl"];
NSString *title = [datadict objectForKey:#"title"];
NSString *description = [datadict objectForKey:#"description"];
NSString *newAddressPartOfURL = [url stringByReplacingOccurrencesOfString:#" " withString:#"+"];
//NSLog([url stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]);
NSURLResponse *urlResponse;
NSData *data = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:newAddressPartOfURL]] returningResponse:&urlResponse error:nil];
// Configure the cell.
UIImage *urlImage = [[UIImage alloc] initWithData:data];
// NSLog(#"%i",[imageView.image topCapHeight]);
cell.title.text = title;
cell.description.text = description;
cell.image.image = urlImage;
[urlImage release];
}
return cell;
}
Doing synchronous downloads as your cells are being drawn is definitely going to cause some unsmooth scrolling. You could try to replace those with asynchronous calls, and filling in the data with a generic object while the download is happening. When the download completes, then call reloadData on your tableview.
afaik the dequeueReusableCellWithIdentifier method is called as cells get flush etc. Build your data / do the requests on init, not in the cell creation!

Resources