I have a simple iOS app which parses multiple JSON feeds and stores the data in multiple strings. I know exactly which strings to use for what and how long the count is because the JSON feeds are feeds that I control from some of my websites.
However, even though I have specified this in the "tableView cellForRowAtIndexPath" method, the UITableView still won't populate..
Is this because I am using strings to populate the UITableView? And if so, do you HAVE to use arrays to populate a UITableView.
Thanks for you're time :)
UPDATE: Here is m code:
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 5;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"Printing table view.");
static NSString *CellIdentifier = #"Cell";
AccountCell *cell = (AccountCell *)[account_table dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"AccountCell" owner:self options:nil];
cell = [nib objectAtIndex: 0];
// Draws the cell background.
cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"uiFeedletsnglass5.png"]];
// Draws the pressed cell background.
cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"cell-on.png"]];
// Round of edges of content view in Carousel.
cell.layer.cornerRadius = 5;
cell.layer.masksToBounds = YES;
cell.layer.borderWidth = 1.0f;
cell.layer.borderColor = [[UIColor grayColor] CGColor];
cell.profilepic.layer.cornerRadius = 5;
cell.profilepic.layer.masksToBounds = YES;
cell.profilepic.layer.borderWidth = 1.0f;
cell.profilepic.layer.borderColor = [[UIColor grayColor] CGColor];
}
if ((facebook_printed == 0) && (logged_facebook == 1)) {
NSString *full_name = [NSString stringWithFormat:#"%# %#", facebook_first_name, facebook_last_name];
cell.username.text = [NSString stringWithFormat:#"%#", full_name];
cell.account_type_name.text = [NSString stringWithFormat:#"Facebook"];
NSData *facebook_imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString: facebook_proffile_pic]];
UIImage *facebook_image = [[UIImage alloc] initWithData:facebook_imageData];
cell.profilepic.image = facebook_image;
facebook_printed = 1;
}
else if ((youtube_printed == 0) && (logged_youtube == 1)) {
cell.username.text = [NSString stringWithFormat:#"%#", youtube_profilename];
cell.account_type_name.text = [NSString stringWithFormat:#"YouTube"];
NSData *youtube_imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString: youtube_profilepic]];
UIImage *youtube_image = [[UIImage alloc] initWithData:youtube_imageData];
cell.profilepic.image = youtube_image;
youtube_printed = 1;
}
else if ((instagram_printed == 0) && (logged_instagram == 1)) {
cell.username.text = [NSString stringWithFormat:#"%#", instagram_name_tag];
cell.account_type_name.text = [NSString stringWithFormat:#"Instagram"];
NSData *instagram_imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString: instagram_profilepicture]];
UIImage *instagram_image = [[UIImage alloc] initWithData:instagram_imageData];
cell.profilepic.image = instagram_image;
instagram_printed = 1;
}
else if ((googleplus_printed == 0) && (logged_googleplus == 1)) {
cell.username.text = [NSString stringWithFormat:#"%#", googleplus_profilename];
cell.account_type_name.text = [NSString stringWithFormat:#"Google Plus"];
NSData *googleplus_imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString: googleplus_profilepic]];
UIImage *googleplus_image = [[UIImage alloc] initWithData:googleplus_imageData];
cell.profilepic.image = googleplus_image;
googleplus_printed = 1;
}
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
return cell;
}
Maybe try reloading the table view's data once you obtain the value of the string?
[tableView reloadData];
Right after much frustration and pretty much a lot of trial and error I finally figured out that it is because of if (cell == nil) that my Custom Cell was not loading (showing in the UITableView).
I was not aware of this at all, but from what I have read online it seems that when using UiTableViews in Storyboard UI's with Custom Cells, you are NOT meant to use the control statement if (cell == nil)
Thanks to everyone who commented on this post though. I appreciate you're help.
Related
Due to some permission issue, in my tableView some cell can be selected by user and some cell can't be selected by that user. What I did in my cellForRowAtIndexPath is:
-(UITableViewCell *) tableView:(UITableView *) tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
int row = (int)[indexPath row];
static NSString *simpleTableIdentifier = #"EditProjectTableCell";
Project* project = (Project*)[self.projectList objectAtIndex:row];
EditProjectTableCell *cell = (EditProjectTableCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:simpleTableIdentifier owner:self options:nil];
cell = [nib objectAtIndex:0];
cell.serial.layer.cornerRadius = 5;
cell.accessoryView = [[ UIImageView alloc ] initWithImage:[UIImage imageNamed:#"accessory_right.png"]];
cell.cellView.backgroundColor = [UIColor blackColor];
cell.backgroundColor = [UIColor blackColor];
}
if ([project.role isEqualToString:#"1"] || [project.role isEqualToString:#"2"]) {
UIView *customView = [[UIView alloc] initWithFrame:cell.frame];
customView.backgroundColor = [UIColor clearColor];
cell.selectedBackgroundView = customView;
}
else cell.selectionStyle = UITableViewCellSelectionStyleNone;
if(cell.imageFetchOperation != nil) [cell.imageFetchOperation cancel];
cell.imageFetchOperation = [[CellBlockOperation alloc] initWithIndexPath:indexPath
andPkId:project.pkId
andFetchImage:YES
andFetchReportCounter:NO
andFetchIssueCounter:NO
andFetchDrawingCounter:NO
andDelegate:self];
if(cell.counterFetchOperation != nil) [cell.counterFetchOperation cancel];
cell.counterFetchOperation = [[CellBlockOperation alloc] initWithIndexPath:indexPath
andPkId:project.pkId
andFetchImage:NO
andFetchReportCounter:YES
andFetchIssueCounter:NO
andFetchDrawingCounter:NO
andDelegate:self];
cell.projectName.text = project.name;
cell.projectNumber.text = project.number;
cell.owner.text = [NSString stringWithFormat:#"%# %#",project.ownerName,project.ownerLastName];
NSString* temp_date = [Utils stringFromDateForGUI:project.creationDate];
cell.date.text = temp_date;
[cell.syncStatusView setImage:[Utils getImageForSyncStatus:project.isDirty.intValue]];
NSNumber *ret = [self.reportCountList objectForKey:project.pkId];
if(ret == nil) {
cell.serial.text = #"";
[cell.counterFetchOperation setPkId:project.pkId];
[self.tableCellUpdateQueue addOperation:cell.counterFetchOperation];
} else {
cell.serial.text = [NSString stringWithFormat:#"%d",[ret intValue]];
}
id img = [self getSmallImage:project.pkId andIndexPath:indexPath andCell:cell];
if(img == nil || img == (id)[NSNull null]) {
img = [UIImage imageNamed:#"gray-img.jpg"];
cell.iconImageView.image = [UIImage imageNamed:#"project-icon.png"];
cell.iconImageView.hidden = NO;
} else {
cell.iconImageView.hidden = YES;
}
cell.imageView.image = (UIImage*)img;
if ([project.role isEqualToString:#"2"] || [project.role isEqualToString:#"1"])
cell.selectImageView.hidden = NO;
else
cell.selectImageView.hidden = YES;
return cell;
}
Selection part is working just fine. But if a cell is selected then the background color of a UILabel gets changed to clear color. See the below images for clear idea.
Before selection:
After Selection :
i have a table with a custom cell. This cell have a label that i would like move in cell (if a condition is true). Why the position of label is updated only if the cellForRowAtIndexPath method for that cell is called for the second time?
This is the first question.
The second question is is as follows:
The custom cell contain a view, in this view i programmatically add images. If i have two sections in the table, after scrolling the table, the images of first cell in first section appear in the first cell of second section. Why?
This is the code
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *idDettCal = #"cellaVotoCalciatore";
NSString *idRiepilogo = #"riepilogoCell";
NSString *idTotali = #"bonusTotaliCell";
//Dictionary per Titolari e Panchinari
NSDictionary *calciatore = [[NSDictionary alloc] init];
if (indexPath.section == 0 || indexPath.section == 1) {
foaVotoCalciatoreCell *cell = (foaVotoCalciatoreCell *)[tableView dequeueReusableCellWithIdentifier:idDettCal];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:idDettCal owner:self options:nil];
cell = [nib objectAtIndex:0];
}
//TITOLARI
if (indexPath.section == 0) {
calciatore = [titolari objectAtIndex:indexPath.row];
}
//PANCHINARI
else if (indexPath.section == 1) {
calciatore = [panchinari objectAtIndex:indexPath.row];
}
NSString *calciatoreStr =
[NSString stringWithFormat:#"%#%#%#%#",
[calciatore objectForKey:#"CALCIATORE"],
#" (",
[[calciatore objectForKey:#"SQUADRA"] substringToIndex:3],
#")"];
NSString *imgRuolo =
[NSString stringWithFormat:#"%#%#",
[calciatore objectForKey:#"RUOLO"],
#".jpg"];
cell.ruolo.image = [UIImage imageNamed:imgRuolo];
NSDictionary *dettaglioVoto = [[NSDictionary alloc] init];
UIImageView *imageIcona;
CGFloat offset;
dettaglioVoto = [calciatore objectForKey:#"VOTO_STM"];
offset = 0;
for (NSString *icona in dettaglioVoto) {
if ([icona isEqualToString: #"AMMONITO"]) {
imageIcona = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"amm.png"]];
}
else if ([icona isEqualToString: #"GOL_FATTO"]) {
imageIcona = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"golfatto.png"]];
}
else if ([icona isEqualToString: #"GOL_SUBITO"]) {
imageIcona = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"golsubito.png"]];
}
else if ([icona isEqualToString: #"ENTRATO"]) {
imageIcona = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"entrato.png"]];
}
else if ([icona isEqualToString: #"USCITO"]) {
imageIcona = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"uscito.png"]];
}
else if ([icona isEqualToString: #"ESPULSO"]) {
imageIcona = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"esp.png"]];
}
else if ([icona isEqualToString: #"ASSIST"]) {
imageIcona = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"assist.png"]];
}
else if ([icona isEqualToString: #"ASSIST_FERMO"]) {
imageIcona = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"assistf.png"]];
}
else if ([icona isEqualToString: #"RIGORE_SEGNATO"]) {
imageIcona = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"rigoresegnato.png"]];
}
else if ([icona isEqualToString: #"RIGORE_SBAGLIATO"]) {
imageIcona = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"rigoresbagliato.png"]];
}
else if ([icona isEqualToString: #"RIGORE_PARATO"]) {
imageIcona = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"rigoreparato.png"]];
}
else if ([icona isEqualToString: #"AUTOGOL"]) {
imageIcona = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"autogol.png"]];
}
else if ([icona isEqualToString: #"GOL_PARTITA"]) {
imageIcona = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"golvittoria.png"]];
}
else if ([icona isEqualToString: #"GOL_PAREGGIO"]) {
imageIcona = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"golpareggio.png"]];
}
imageIcona.frame = CGRectMake(offset, 0, imageIcona.frame.size.width, imageIcona.frame.size.height);
offset = imageIcona.frame.size.width + offset + 2;
[cell.iconeDettaglio addSubview: imageIcona];
}
if (offset == 0) {
cell.calciatore.frame = CGRectMake(cell.calciatore.frame.origin.x, 14, cell.calciatore.frame.size.width, cell.calciatore.frame.size.height);
cell.iconeDettaglio.hidden = YES;
}
cell.calciatore.text = calciatoreStr;
cell.votoIniziale.text = [calciatore objectForKey:#"VOTO_PRNT"];
cell.votoFinale.text = [calciatore objectForKey:#"VOTO_PRNT_TOT"];
return cell;
}
//La giornata è calcolata. Sezione 2 = BONUS e TOTALI
else if (variabiliGlobali.gioCalcolata && indexPath.section == 2) {
NSDictionary *totaliVal;
NSDictionary *totaliTip;
totaliVal = [logCalValore objectAtIndex:indexPath.row];
totaliTip = [logCalTipo objectAtIndex:indexPath.row];
foaBonusTotaliCell *cell = (foaBonusTotaliCell *)[tableView dequeueReusableCellWithIdentifier:idTotali];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:idTotali owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.tipoBonusLabel.text = totaliTip;
cell.totaleLabel.text = totaliVal;
return cell;
}
else {
NSDictionary *riepilogoVal;
NSDictionary *riepilogoTip;
riepilogoVal = [logForValore objectAtIndex:indexPath.row];
riepilogoTip = [logForTipo objectAtIndex:indexPath.row];
foaRiepilogoCell *cell = (foaRiepilogoCell *)[tableView dequeueReusableCellWithIdentifier:idRiepilogo];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:idRiepilogo owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.voceRiepilogoLabel.text = riepilogoTip;
cell.valoreRiepilogoLabel.text = riepilogoVal;
return cell;
}
}
Thanks in advance.
First Question: Which label? What condition? Are you talking about this:
if (offset == 0) {
cell.calciatore.frame = CGRectMake(cell.calciatore.frame.origin.x, 14, cell.calciatore.frame.size.width, cell.calciatore.frame.size.height);
cell.iconeDettaglio.hidden = YES;
}
You have to be more specific here!
Second Question: The reason that wrong images show up in wrong cells is that your cells are being reused by the tableView. Make sure to set the custom cell's label.texts and imageView.images to nil right after dequeueReusableCellWithIdentifier: to ensure they are empty when reused.
WARNING: This is NOT a good idea:
[cell.iconeDettaglio addSubview: imageIcona];
Because your cell is being reused, and once reused, you'll see the previous imageIcona and add ANOTHER imageIcona on top as a subview. Make the imageIcona an IBOUTLET or property of your custom cell, and only set its image variable in cellForRowAtIndexPath:.
First question: I can't debug for you, but without running the code, i can imagine that this part of the code
if (offset == 0) {
cell.calciatore.frame = CGRectMake(cell.calciatore.frame.origin.x, 14, cell.calciatore.frame.size.width, cell.calciatore.frame.size.height);
cell.iconeDettaglio.hidden = YES;
}
is never reached the first time because of this other part of code
offset = imageIcona.frame.size.width + offset + 2;.
And after you scroll, this loop for (NSString *icona in dettaglioVoto) { is not performed because maybe dettaglioVoto is empty, and so the offset will remain equals to zero, and you will have it the way you want. But i can't be sure without you debugging your code to see why the if is not being reached the first time.
Second question: I don't think you are properly using the reuse mechanism for cells. So, if you are going to reuse the cells, you should use set prepareForReuse method in the cell code, like this:
-(void) prepareForReuse {
// Your code code here: like clearing old images and text and/or setting new images or text
}
Also, it normally works better if you register the nib for the table view, this way:
foaVotoCalciatoreCell *cell = (foaVotoCalciatoreCell *)[tableView dequeueReusableCellWithIdentifier:idDettCal];
if (cell == nil)
{
[[self tableView] registerNib:[UINib nibWithNibName:loadNibNamed:idDettCal bundle:nil]
forCellReuseIdentifier:nibWithNibName:loadNibNamed:idDettCal];
}
I am creating a scrollable UITableView in which each cell requires to make a call to the Google Directions Matrix API.For some reason,each time I scroll it makes the call and does the calculations separately which significantly takes a toll on the responsiveness of the scrolling.Here's the code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(tableView.tag == 1) {
return [self specialTableViewCell: tableView];
}
static NSString *CellIdentifier = #"OfferCell";
OTNOfferCell *cell = (OTNOfferCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
// create cell using style Subtitle
cell = [[OTNOfferCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
}
PFObject *venue = [self.venues objectAtIndex:indexPath.section];
cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"MainPage Item.png"]];
cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"MainPageItemSelected.png"]];
cell.clubNameLabel.text = [venue valueForKey: #"name"] ;
PFFile *photo = [venue objectForKey:#"logo"];
NSData *data = [photo getData];
UIImage *image = [UIImage imageWithData: data];
cell.clubLogoImageView.image = image;
int count = [[venue valueForKey:#"events"] count];
if(count == 1)
{
cell.numberOfEventsLabel.text = #"1 Event";
}
else
{
cell.numberOfEventsLabel.text = [NSString stringWithFormat:#"%d Events", count];
}
PFGeoPoint *destinationLocation = [venue objectForKey:#"geopoint"];
locationManager = [[CLLocationManager alloc] init];
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
[locationManager startUpdatingLocation];
PFGeoPoint *currentLocation = [PFGeoPoint geoPointWithLatitude:locationManager.location.coordinate.latitude longitude:locationManager.location.coordinate.longitude];
NSString *current = [venue objectForKey:#"address"];
NSLog(#"%#",current);
NSString *urlString = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/distancematrix/json?origins=%#&destinations=San+Francisco&mode=driving&language=en&sensor=true&units=imperial",current];
NSURL *url = [NSURL
URLWithString:[urlString
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSData *googledata = [NSData dataWithContentsOfURL:url];
NSError *error;
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:googledata options:kNilOptions error:&error];
NSString *result = [[[[[[json objectForKey:#"rows"] objectAtIndex: 0] objectForKey:#"elements"] objectAtIndex:0]objectForKey:#"distance"]objectForKey:#"text"];
double tempd = [currentLocation distanceInMilesTo:destinationLocation];
NSString *distance = [NSString stringWithFormat:#"%f",tempd];
NSString *distanceTrunc = [distance substringToIndex: MIN(3, [distance length])];
cell.distanceLabel.text = [NSString stringWithFormat:#"%# mi", distanceTrunc];
return cell;
}
Is there any way to fix this,wherein the calculation is done only once.
You should not be making these calculations in the cell. UITableViewCells are part of the view layer.
You should make the requests in your controller and store the results in something like an NSArray. Then cellForRowAtIndexPath should just pull data from that array.
My app is scrolling and Searching very slow when I have Images set for each cell.Pictures lifted faster, but still slow when searching. Here is my code in the cell at row. Any ideas?
#interface UIImage (TPAdditions)
- (UIImage*)imageScaledToSize:(CGSize)size;
#end
#implementation UIImage (TPAdditions)
- (UIImage*)imageScaledToSize:(CGSize)size {
UIGraphicsBeginImageContext(size);
[self drawInRect:CGRectMake(0, 0, size.width, size.height)];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
#end
cellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
static NSInteger buton1_tag = 100;
static NSInteger buton2_tag = 101;
if (indexPath.section == 0) {
CellIdentifier = #"CellMuzikEkle";
}else{
if(indexPath.row == 0 && !self.editing)
CellIdentifier = #"CellPlayereEkle";
else
CellIdentifier = #"CellDizi";
}
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
if (indexPath.section == 1 && indexPath.row == 0 && !self.editing) // Grubu ekle
cell = [[[NSBundle mainBundle] loadNibNamed:#"Cell4" owner:self options:nil] objectAtIndex:0];
else{
if (indexPath.section == 0) {
cell = [[[NSBundle mainBundle] loadNibNamed:#"Cell" owner:self options:nil] objectAtIndex:5];
UIButton *ipodbuton = (UIButton *) [cell.contentView viewWithTag:buton1_tag];
[ipodbuton addTarget:self action:#selector(iPoddan_Ekle:) forControlEvents:UIControlEventTouchUpInside];
UIButton *yuklenenler = (UIButton *) [cell.contentView viewWithTag:buton2_tag];
[yuklenenler addTarget:self action:#selector(Yuklenenlerden_Ekle:) forControlEvents:UIControlEventTouchUpInside];
}else{
cell.textLabel.font = [UIFont boldSystemFontOfSize:15.0];
cell.textLabel.numberOfLines=2;
cell.detailTextLabel.font = [UIFont systemFontOfSize:13];
[cell.imageView.layer setBorderWidth: 1.5];
}
}
}
if (indexPath.section == 1 && !self.editing && indexPath.row != 0)
cell.accessoryType =UITableViewCellAccessoryDetailDisclosureButton;
else
cell.accessoryType =UITableViewCellAccessoryNone;
if(indexPath.section == 0){
cell.textLabel.text = #"";
cell.detailTextLabel.text = #"";
cell.imageView.image = nil;
}else{
if (indexPath.row > 0 || self.editing) {
if (!self.editing)
indexPath = [NSIndexPath indexPathForRow:indexPath.row - 1 inSection:indexPath.section];
NSArray *aradizi = tableView == self.searchDisplayController.searchResultsTableView ? [[NSArray alloc] initWithArray:self.filteredListContent] : [[NSArray alloc] initWithArray:self.dizi];
if ([[NSUserDefaults standardUserDefaults] boolForKey:cellresimyuk_s])
cell.imageView.image = [[self Resim_Artwork:[aradizi objectAtIndex:indexPath.row]] imageScaledToSize:CGSizeMake(65, 50)];
else
cell.imageView.image = nil;
cell.textLabel.text = [[aradizi objectAtIndex:indexPath.row] objectForKey:isim_s];
NSTimeInterval theTimeInterval = [[[aradizi objectAtIndex:indexPath.row] objectForKey:sure_s] intValue] - 1;
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
NSDate *date1;
if (theTimeInterval >= 3600) {
[dateFormatter setDateFormat:#"HH:mm:ss"];
date1 = [dateFormatter dateFromString:#"00:00:00"];
}else{
[dateFormatter setDateFormat:#"mm:ss"];
date1 = [dateFormatter dateFromString:#"00:00"];
}
NSDate *date2 = [[NSDate alloc] initWithTimeInterval:theTimeInterval sinceDate:date1];
cell.detailTextLabel.text = [dateFormatter stringFromDate:date2];
}else{
if (tableView == self.searchDisplayController.searchResultsTableView)
cell.textLabel.text = AramaSonuclrPlayerEkle_lclz;
else
cell.textLabel.text = GrubuPlayereEkle_lclz;
}
}
return cell;
}
Resim_Artwork
- (UIImage *)Resim_Artwork:(NSDictionary *)dictr{
if ([dictr objectForKey:videoid_s]) {
if ([self Dosya_Varmi:[[rsm_favori stringByAppendingPathComponent:[dictr objectForKey:videoid_s]] stringByAppendingPathExtension:#"png"]])
return [UIImage imageWithContentsOfFile:[[rsm_favori stringByAppendingPathComponent:[dictr objectForKey:videoid_s]] stringByAppendingPathExtension:#"png"]];
}else{
if ([[[dictr objectForKey:urlsi_s] pathExtension] isEqualToString:#"mp4"]) {
AVURLAsset *assetresim = [[AVURLAsset alloc] initWithURL:[NSURL fileURLWithPath:[kDocdir stringByAppendingPathComponent:[dictr objectForKey:urlsi_s]]] options:nil];
AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:assetresim];
gen.appliesPreferredTrackTransform = YES;
int suresi = CMTimeGetSeconds(assetresim.duration);
if (suresi > 0) {
CMTime time;
if (suresi>6)
time = CMTimeMakeWithSeconds(6.0, 600);
else
time = CMTimeMakeWithSeconds(0.0, 600);
NSError *error = nil;
CMTime actualTime;
CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
UIImage *thumb = [[UIImage alloc] initWithCGImage:image];
CGImageRelease(image);
return thumb;
}
}else {
if ([dictr objectForKey:kaynak_s]) {
AVAsset *asset = [AVURLAsset URLAssetWithURL:[NSURL URLWithString:[dictr objectForKey:urlsi_s]] options:nil];
for ( AVMetadataItem* item in [asset commonMetadata] ) {
if ([[item commonKey] isEqualToString:#"artwork"] )
if (item.dataValue != nil)
if ([UIImage imageWithData:item.dataValue])
return [UIImage imageWithData:item.dataValue];
}
}else{
if ([self Dosya_Varmi:[kDocdir stringByAppendingPathComponent:[dictr objectForKey:urlsi_s]]]){
AVAsset *asset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:[kDocdir stringByAppendingPathComponent:[dictr objectForKey:urlsi_s]]] options:nil];
for ( AVMetadataItem* item in [asset commonMetadata] ) {
if ([[item commonKey] isEqualToString:#"artwork"] )
if (item.dataValue != nil)
if ([UIImage imageWithData:item.dataValue])
return [UIImage imageWithData:item.dataValue];
}
}
}
}
}
return [self Resimm:#".varsayilan" Koordinat:CGRectMake(120,1320, 80, 60) retinami:0 grubu:6];
}
tableView willDisplayCell
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
NSArray *viewControllers = [self.tabBarController viewControllers];
NSArray *viewControllers2 = [[viewControllers objectAtIndex:0] viewControllers];
Player *detailViewController = (Player *)[viewControllers2 objectAtIndex:0];
[detailViewController.temalar Cell_Tema:cell];
cell.textLabel.backgroundColor = [UIColor clearColor];
cell.detailTextLabel.backgroundColor = [UIColor clearColor];
cell.textLabel.textColor = [detailViewController.temalar Baslik_Renk];
cell.detailTextLabel.textColor = [detailViewController.temalar Bilgi_Renk];
[cell.imageView.layer setBorderColor: [tableView.separatorColor CGColor]];
[((UIButton *) [cell.contentView viewWithTag:100]) setBackgroundImage:[self Resimm:#".buton" Koordinat:CGRectMake(0,1350, 94, 35) retinami:0 grubu:7] forState:UIControlStateNormal];
[((UIButton *) [cell.contentView viewWithTag:100]) setTitleColor:[detailViewController.temalar Baslik_Renk] forState:UIControlStateNormal];
[((UIButton *) [cell.contentView viewWithTag:101]) setBackgroundImage:[self Resimm:#".buton" Koordinat:CGRectMake(0,1350, 94, 35) retinami:0 grubu:7] forState:UIControlStateNormal];
[((UIButton *) [cell.contentView viewWithTag:101]) setTitleColor:[detailViewController.temalar Baslik_Renk] forState:UIControlStateNormal];
}
Here:
NSArray *aradizi = tableView == self.searchDisplayController.searchResultsTableView ?
[[NSArray alloc] initWithArray:self.filteredListContent] :
[[NSArray alloc] initWithArray:self.dizi];
You should avoid creating objects inside cellForRowAtIndexPath wherever possible.
Anyway you don't need to:
NSArray *aradizi = tableView == self.searchDisplayController.searchResultsTableView ?
self.filteredListContent :
self.dizi;
Here you seem to be creating and resizing thumbnails on the fly. :
if ([[NSUserDefaults standardUserDefaults] boolForKey:cellresimyuk_s])
cell.imageView.image = [[self Resim_Artwork:[aradizi objectAtIndex:indexPath.row]]
imageScaledToSize:CGSizeMake(65, 50)];
This is bound to jam up smooth tableView scolling. All of these should be pre-processed and cached, or at least only processed once here and cached for reuse.
Time-consuming nonUI processing like this can go onto another thread so that your scolling stays smooth even if the image isn't ready to show. Something like…
if ([[NSUserDefaults standardUserDefaults] boolForKey:cellresimyuk_s])
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UIImage* image =
[[self Resim_Artwork:[aradizi objectAtIndex:indexPath.row]]
imageScaledToSize:CGSizeMake(65, 50)];
dispatch_async(dispatch_get_main_queue(), ^{
//check our cell is still valid
if ([[self.tableView cellForRowAtIndexPath:indexPath] isEqual:cell]){
cell.imageView.image = image;
}
});
});
else
cell.imageView.image = nil;
Regarding the date formatter: these are heavyweight objects, you need to ensure to only create once, keep in a property for reuse. I suggest you do the following:
Declare two date formatter properties and another for your zero'd date. Initialise them all in viewDidLoad:
- (void)viewDidLoad {
[super viewDidLoad];
self.hoursFormat = [[NSDateFormatter alloc] init];
[self.hoursFormat setDateFormat:#"HH:mm:ss"];
self.minsFormat = [[NSDateFormatter alloc]init];
[self.minsFormat setDateFormat:#"mm:ss"];
self.zeroDate = [self.hoursFormat dateFromString:#"00:00:00"];
}
Then in cellForRowAtIndexPath:
NSDate* date = [self.zeroDate dateByAddingTimeInterval:theTimeInterval];
if (theTimeInterval >= 3600) {
self.label.text = [self.hoursFormat stringFromDate:date];
} else {
self.label.text = [self.minsFormat stringFromDate:date];
}
He Was, Thank you for the answer. performance was very nice. But since I made this change, the program closes.
new codes:
NSMutableArray *aradizi;
if (tableView == self.searchDisplayController.searchResultsTableView)
aradizi = self.filteredListContent;
if (indexPath.section == 2 && tableView != self.searchDisplayController.searchResultsTableView)
aradizi = self.dizi_klasorler;
if (indexPath.section == 3)
aradizi = self.dizi_veriler;
if ([[NSUserDefaults standardUserDefaults] boolForKey:cellresimyuk_s]){
if (cell.imageView.image == nil)
cell.imageView.image = [[self Resimm:#".varsayilan" Koordinat:CGRectMake(120,1320, 80, 60) retinami:0 grubu:6] Resim_Skala:CGSizeMake(60, 45)];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UIImage* image = [[self Resim_Artwork:[[aradizi objectAtIndex:indexPath.row] objectForKey:urlsi_s]] Resim_Skala:CGSizeMake(60, 45)];
dispatch_async(dispatch_get_main_queue(), ^{
//check our cell is still valid
if (tableView == self.searchDisplayController.searchResultsTableView){
if ([[self.searchDisplayController.searchResultsTableView cellForRowAtIndexPath:indexPath] isEqual:cell])
cell.imageView.image = image;
}else{
if ([[self.tableView cellForRowAtIndexPath:indexPath] isEqual:cell])
cell.imageView.image = image;
}
});
});
}else
cell.imageView.image = nil;
http://img29.imageshack.us/img29/1083/ekranresmi2013020301553.png
http://img502.imageshack.us/img502/5591/ekranresmi2013012919525.png
im newbie IOS and using IB, im working UITableView in UIViewController, i have implement "UITableViewDelegate, UITableViewDataSource" in viewcontroller and setdelegate,datasource for uitableview but it dosen't work, i dont know,
please help me!
thank for your read this article.
code viewcontroller.h
#interface ViewController : UIViewController<UITableViewDelegate,
UITableViewDataSource> #property (nonatomic, retain) IBOutlet UITableView *tableView;
code viewcontroller.m
- (void)viewDidLoad { [tableView setDataSource:self];
[tableView setDelegate:self];
dispatch_async(htvque, ^{
NSData* data = [NSData dataWithContentsOfURL: listFilmByCate];
NSError* error;
jsonTable = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
listDataTable = [jsonTable objectForKey:#"List"];
dispatch_async(dispatch_get_main_queue(), ^{
[tableView reloadData];
});
});
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return listDataTable.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *dataTable = [listDataTable objectAtIndex:indexPath.row];
NSData *receivedData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[[dataTable objectForKey:#"Thumbnail"]objectForKey:#"Url1"]]]; UIImage *image = [[[UIImage alloc] initWithData:receivedData] stretchableImageWithLeftCapWidth:50 topCapHeight:80];
static NSString *simple_cell = #"simpleCell";
CustomizeCell_Home *customize_cell = (CustomizeCell_Home *)[tableView dequeueReusableCellWithIdentifier:simple_cell];
if (simple_cell == nil)
{}
customize_cell.imageView.image = image;
customize_cell.lbldescription.text =[dataTable objectForKey:#"LongDescription"];
customize_cell.lblTitle.text = [dataTable objectForKey:#"VName"];
customize_cell.lblTitle.lineBreakMode = UILineBreakModeWordWrap | UILineBreakModeTailTruncation;
customize_cell.lbldescription.lineBreakMode = UILineBreakModeWordWrap | UILineBreakModeTailTruncation;
customize_cell.lbldescription.numberOfLines=4;
customize_cell.contentView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"bgtblRight.png"]];
return customize_cell;
}
in this line of code is your problem:
CustomizeCell_Home *customize_cell = (CustomizeCell_Home *)[tableView dequeueReusableCellWithIdentifier:simple_cell];
if (simple_cell == nil)
{}
what would happens if customize_cell is nil?
you are not instanciating the customize_cell and because of that you cant call these methods:
customize_cell.imageView.image = image;
customize_cell.lbldescription.text =[dataTable objectForKey:#"LongDescription"];
customize_cell.lblTitle.text = [dataTable objectForKey:#"VName"];
customize_cell.lblTitle.lineBreakMode = UILineBreakModeWordWrap | UILineBreakModeTailTruncation;
customize_cell.lbldescription.lineBreakMode = UILineBreakModeWordWrap | UILineBreakModeTailTruncation;
customize_cell.lbldescription.numberOfLines=4;
customize_cell.contentView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"bgtblRight.png"]];
return customize_cell;
just add a simple inicialize cell inside the if, like this:
if (customize_cell == nil)
{
customize_cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:#"AnIdentifierString"] autorelease];
}
EDIT
change this:
CustomizeCell_Home *customize_cell = (CustomizeCell_Home *)[tableView dequeueReusableCellWithIdentifier:simple_cell];
if (simple_cell == nil)
{}
customize_cell.lbldescription.text =[dataTable objectForKey:#"LongDescription"];
customize_cell.lblTitle.text = [dataTable objectForKey:#"VName"];
customize_cell.lblTitle.lineBreakMode = UILineBreakModeWordWrap | UILineBreakModeTailTruncation;
customize_cell.lbldescription.lineBreakMode = UILineBreakModeWordWrap | UILineBreakModeTailTruncation;
customize_cell.lbldescription.numberOfLines=4;
customize_cell.contentView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"bgtblRight.png"]];
return customize_cell;
to:
CustomizeCell_Home *customize_cell = (CustomizeCell_Home *)[tableView dequeueReusableCellWithIdentifier:simple_cell];
if (customize_cell == nil)
{
customize_cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:#"AnIdentifierString"] autorelease];
}
customize_cell.lbldescription.text =[dataTable objectForKey:#"LongDescription"];
customize_cell.lblTitle.text = [dataTable objectForKey:#"VName"];
customize_cell.lblTitle.lineBreakMode = UILineBreakModeWordWrap | UILineBreakModeTailTruncation;
customize_cell.lbldescription.lineBreakMode = UILineBreakModeWordWrap | UILineBreakModeTailTruncation;
customize_cell.lbldescription.numberOfLines=4;
customize_cell.contentView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"bgtblRight.png"]];
return customize_cell;
Set,
tableView. dataSource = self;
tableView. delegate = self;
Implement protocol which are directed as #required means to say mandatory
-(UITableViewCell*) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath
{
// dint concentrate on this part, hope u are right
NSDictionary *dataTable = [listDataTable objectAtIndex:indexPath.row];
NSData *receivedData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[[dataTable objectForKey:#"Thumbnail"]objectForKey:#"Url1"]]];
UIImage *image = [[[UIImage alloc] initWithData:receivedData] stretchableImageWithLeftCapWidth:50 topCapHeight:80];
static NSString *simple_cell = #"simpleCell";
// works like double ended queue.... cells are re-used when available... so when cell is nil, u need to create
CustomizeCell_Home *customize_cell = (CustomizeCell_Home *)[tableView dequeueReusableCellWithIdentifier:simple_cell];
if (simple_cell == nil)
{
// CustomizeCell_Home is linked to CustomizeCell_Home_Reference using nib,
[[NSBundle mainBundle] loadNibNamed: #"CustomizeCell_Home" owner: self options: nil];
customize_cell = CustomizeCell_Home_Reference;
}
.....
.....
return customize_cell;
}
First thing, the cells are never allocated, instead of doing if(simple_cell==nil), you should do if(customize_cell==nil) and do the initialization code there. Otherwise you're comparing a string that you just created and set a value to against nil.