i have a problem with my app crashing when my custom TableViewCell gets released.
the Cell gets initialized like the following in cellForRowAtIndexPath:
SearchTableViewCell *cell = (SearchTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[SearchTableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
cell.nameLabel.text = #"some text";
cell.addressLabel.text = #"some more text";
the cell class itself looks like this
#import <UIKit/UIKit.h>
#class EGOImageView;
#interface SearchTableViewCell : UITableViewCell {
UILabel *nameLabel;
UILabel *addressLabel;
EGOImageView *imageView;
}
#property (nonatomic, retain) UILabel *nameLabel;
#property (nonatomic, retain) UILabel *addressLabel;
- (UILabel *)labelWithColor:(UIColor*)color selectedColor:(UIColor*)selectedColor fontSize:(CGFloat)fontSize bold:(BOOL)bold frame:(CGRect)rect;
- (void)setThumb:(NSString*)thumb;
#end
.m
#import "SearchTableViewCell.h"
#import "EGOImageView.h"
#import "UIView+Additions.h"
#implementation SearchTableViewCell
#synthesize nameLabel = _nameLabel, addressLabel = _addressLabel;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
if ((self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) {
// Initialization code
UIView *myContentView = self.contentView;
// Name
_nameLabel = [self labelWithColor:[UIColor blackColor] selectedColor:[UIColor whiteColor] fontSize:16.0f bold:YES frame:CGRectMake(140.0f, 16.0f, 181.0f, 21.0f)];
[myContentView addSubview:_nameLabel];
[_nameLabel release];
// Adress
_addressLabel = [self labelWithColor:[UIColor blackColor] selectedColor:[UIColor whiteColor] fontSize:13.0f bold:YES frame:CGRectMake(140.0f, _nameLabel.bottom, 181.0f, 21.0f)];
[myContentView addSubview:_addressLabel];
[_addressLabel release];
// Image
imageView = [[EGOImageView alloc] initWithPlaceholderImage:[UIImage imageNamed:#"placeholder.png"]];
imageView.frame = CGRectMake(9.0f, 9.0f, 120.0f, 80.0f);
[myContentView addSubview:imageView];
[imageView release];
}
return self;
}
- (UILabel *)labelWithColor:(UIColor*)color selectedColor:(UIColor*)selectedColor fontSize:(CGFloat)fontSize bold:(BOOL)bold frame:(CGRect)rect {
UIFont *font;
if(bold) {
font = [UIFont boldSystemFontOfSize:fontSize];
} else {
font = [UIFont systemFontOfSize:fontSize];
}
UILabel *label = [[UILabel alloc] initWithFrame:rect];
label.backgroundColor = [UIColor clearColor];
label.textColor = color;
label.highlightedTextColor = selectedColor;
label.font = font;
return label;
}
- (void)setThumb:(NSString*)thumb {
imageView.imageURL = [NSURL URLWithString:thumb];
}
- (void)willMoveToSuperview:(UIView *)newSuperview {
[super willMoveToSuperview:newSuperview];
if(!newSuperview) {
[imageView cancelImageLoad];
}
}
- (void)dealloc {
[_addressLabel release];
[_nameLabel release];
[imageView release];
[super dealloc];
}
#end
does anybody have an idea why my app crashes on releasing such a cell? commenting out the 2 labels and the image view on dealloc method, the app doesn't crash, but then there will be a memory leak right?
thanks for all hints! please leave a comment if something is unclear!
imageView is being released twice, once when it is created:
imageView = [[EGOImageView alloc] initWithPlaceholderImage:[UIImage imageNamed:#"placeholder.png"]];
imageView.frame = CGRectMake(9.0f, 9.0f, 120.0f, 80.0f);
[myContentView addSubview:imageView];
[imageView release];
and once in dealloc:
- (void)dealloc {
[_addressLabel release];
[_nameLabel release];
[imageView release];
[super dealloc];
}
You already release the memory for that labels after adding to view,again you are trying to release memory those objects are already relese in dealloc method that's why it is killing.if you remove 3 statements in dealloc method it will not crash.
I think the Problem is that you release your properties direct in the initWithStyle function and additional to that in dealloc again. Try removing the release from initWithStyle:
Furthermore you named your variables without _ in the interface but with _ #synthesize'ing in the implementation
Related
I have inherited some old iOS code and have attempted to integrate it into a new iOS 6 application. I have implemented most of the code and so far everything has worked. I'm now working on the last bit of that old code. I'm implementing a set of views to show a rss for a news section of my app. I've implemented the categories view, which upon selecting an item would display the individual items within that category. However nothing gets displayed. I've made all the modifications that I'm aware of that I needed to do, however I'm no expert at iOS development and am in need of some guidance. Below is a snapshot of the simulator as it's attempting to display the view, and below that is a copy of my .h and .m files. I don't know what is preventing anything in the table from showing up. And preemptive thanks to any help!
here's the snapshot of the simulator
Here is a snapshot of the storyboard showing the linking to the Table View
Here's the .h file
#import <UIKit/UIKit.h>
#import "BlogRssParser.h"
#class BlogRssParser;
#class BlogRssParserDelegate;
#class BlogRss;
#class XMLCategory;
#interface NewsViewController : UIViewController <UITableViewDataSource,UITableViewDelegate, BlogRssParserDelegate> {
BlogRssParser * _rssParser;
XMLCategory * _currItem;
}
#property (nonatomic, retain) BlogRssParser * rssParser;
#property (readwrite, retain) XMLCategory * currItem;
#property (nonatomic, retain) IBOutlet UITableView *itemTableView;
#end
Here is my .m file
#import "NewsViewController.h"
#import "NewsDetailsViewController.h"
#import "BlogRssParser.h"
#import "BlogRss.h"
#import "XMLCategory.h"
#define kLabelTag 1;
#interface NewsViewController ()
#end
#implementation NewsViewController
#synthesize rssParser = _rssParser;
#synthesize currItem = _currItem;
- (void)navBarInit {
UIBarButtonItem *refreshBarButton = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
target:self action:#selector(reloadRss)];
[self.navigationItem setRightBarButtonItem:refreshBarButton animated:YES];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
self.itemTableView.delegate = self;
self.itemTableView.dataSource = self;
- (void) viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[self navBarInit];
[self.itemTableView reloadData];
self.itemTableView.userInteractionEnabled = NO;
}
- (void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
_rssParser = [[BlogRssParser alloc]init];
_rssParser.delegate = self;
[[self rssParser]startProcess:[_currItem categoryId]];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)reloadRss{
[[self rssParser]startProcess:[_currItem categoryId]];
[[self itemTableView]reloadData];
}
- (void)processCompleted{
[[self itemTableView]reloadData];
// _tableView.userInteractionEnabled = YES;
[[self itemTableView]setUserInteractionEnabled:YES];
}
-(void)processHasErrors{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"My Title" message:#"Unable to retrieve the news. Please check if you are connected to the internet."
delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [[[self rssParser]rssItems]count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
const CGFloat LABEL_TITLE_HEIGHT = 70.0;
const CGFloat LABEL_WIDTH = 210.0;
NSString * mediaUrl = [[[[self rssParser]rssItems]objectAtIndex:indexPath.row]mediaUrl];
NSData * imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:mediaUrl]];
UIImage * imageFromImageData;
if (imageData == nil) {
imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:#"http://www.urlForImage.image.png"]];
}
imageFromImageData = [[UIImage alloc] initWithData:imageData];
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:#"rssItemCell"];
if(nil == cell){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"rssItemCell"];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
UILabel * _topLabel =
[[UILabel alloc]
initWithFrame:
CGRectMake(
imageFromImageData.size.width + 10.0,
0.0,
LABEL_WIDTH,
LABEL_TITLE_HEIGHT)];
_topLabel.tag = kLabelTag;
_topLabel.opaque = NO;
_topLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin;
_topLabel.backgroundColor = [UIColor clearColor];
_topLabel.textColor = [UIColor colorWithRed:0.25 green:0.0 blue:0.0 alpha:1.0];
_topLabel.highlightedTextColor = [UIColor colorWithRed:1.0 green:1.0 blue:0.9 alpha:1.0];
_topLabel.font = [UIFont systemFontOfSize:[UIFont labelFontSize]];
_topLabel.numberOfLines = 0;
[cell.contentView addSubview:_topLabel];
}
cell.imageView.image = imageFromImageData;
UILabel * topLabel = (UILabel *)[cell.contentView viewWithTag:1];
topLabel.text = [[[[self rssParser]rssItems]objectAtIndex:indexPath.row]title];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NewsDetailsViewController *tlc = [[DetailsViewController alloc]init];
tlc.currentItem = [[[self rssParser]rssItems]objectAtIndex:indexPath.row];
tlc.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController:tlc animated:YES completion:nil];
}
#end
I could not get a conclusion about the problem you are facing.
But here are few things you should check.
Because i cannot see even an empty table view in your screenshot
Do you have the TableView on the Nib file ?
It is mapped from The Nib file to the IBOutlet itemTableView ?
Add at least one table view cell (Drag and drop one prototype cell)..
like this
Then select that cell and give some name in "Reuse Identifier" with this identifier allow datasource..
First thing I would do is make sure that [[[self rssParser] rssItems] count] is actually returning > 0. Also, is this a copy&paste of your .m file? viewDidLoad is missing the closing brace, but Xcode would catch that.
I hope you can help me to set the background color of my navigation bar. As you can see on the first picture below, the bar is light blue/gray, but i want it to be like the second picture "Favoritter".
I have another viewController in my project (see the second picture "Favoritter") where it works. But I can not see what I'm doing wrong here and the navigationBar will only take this light blue/gray color and not yellow.
My code is like this:
------------------InstantCabAppDelegate.m file-----------START-------
//InstantCabAppDelegate.m file
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Create tabBarController instance
tabBarController = [[UITabBarController alloc] initWithNibName:nil bundle:nil];
// Create instances of navigation controller and view controllers
orderController = [[OrderController2 alloc] initWithNibName:#"Order2" bundle:nil];
UINavigationController* firstnavigationController = [[UINavigationController alloc] initWithRootViewController:orderController];
ICStatusViewController *statusController = [[ICStatusViewController alloc] initWithStatus];
UINavigationController *statusNavController = [[UINavigationController alloc] initWithRootViewController:statusController];
ICSettingsViewController *settingsController = [[ICSettingsViewController alloc] init];
UINavigationController *settingsNavController = [[UINavigationController alloc] initWithRootViewController:settingsController];
UIViewController *company_controller = nil;
company_controller = [[ICCompaniesGridController alloc] initWithCompanies:[[NSArray alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"Companies" ofType:#"plist"]]];
tabBarController.viewControllers = [NSArray arrayWithObjects:firstnavigationController, settingsNavController, statusNavController, company_controller, nil];
[window setRootViewController:tabBarController];
[window makeKeyAndVisible];
return YES;
}
------------------ICStatusViewController.m file-----------START-------
// ICStatusViewController.m file
#import "ICStatusViewController.h"
#import "LocalizationSystem.h"
#import "ICTemporaryStore.h"
#import "Debug.h"
#implementation ICStatusViewController
#synthesize doneCallbackBlock=_doneCallbackBlock, cancelCallbackBlock=_cancelCallbackBlock;
#synthesize myTableView, no_statuses, no_statuses_label, delegate;
- (id)initWithStatus
{
if ((self = [super initWithNibName:#"StatusList" bundle:nil]))
{
self.title = AMLocalizedString(#"kStatusTitle", #"");
self.tabBarItem.image = [UIImage imageNamed:#"status_icon"];
self.no_statuses = AMLocalizedString(#"kStatusListNoStatusList", #"");
first_color = TABLE_VIEW_BACKGROUND_COLOR;
second_color = first_color;
self.doneCallbackBlock = nil;
self.cancelCallbackBlock = nil;
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.parentViewController.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:#"background-nologo"]];
self.view.backgroundColor = [UIColor clearColor];
self.myTableView.backgroundColor = TABLE_VIEW_BACKGROUND_COLOR;
if ([statusObjects count] == 0)
{
self.myTableView.hidden = YES;
self.no_statuses_label.text = self.no_statuses;
self.no_statuses_label.hidden = NO;
no_status_background.hidden = NO;
}
[self.no_statuses_label setTextColor:[UIColor colorWithRed:255.0/255.0 green:255.0/255.0 blue:255.0/255.0 alpha:1.0]];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
if ([statusObjects count] == 0)
{
self.myTableView.hidden = YES;
self.no_statuses_label.text = self.no_statuses;
self.no_statuses_label.hidden = NO;
no_status_background.hidden = NO;
self.navigationItem.rightBarButtonItem = nil;
}
else
{
self.myTableView.hidden = NO;
self.no_statuses_label.hidden = YES;
no_status_background.hidden = YES;
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSInteger retval = 0;
for (int i=0; i<[statusObjects count]; i++)
{
StatusObj *add = [statusObjects getStatusAtIndex:i];
if (add.status_id && [add.status_id length] > 0 && [add.status_type isEqualToString:#"STATUS_ORDER"])
{
retval++;
}
}
return retval;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifierStatus = #"StatusCell";
__unsafe_unretained NSString *CellIdentifier = CellIdentifierStatus;
StatusCell* cell = (StatusCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[StatusCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
[[cell textLabel] setTextColor:TABLE_VIEW_TEXT_LABEL_COLOR];
[[cell detailTextLabel] setTextColor:TABLE_VIEW_DETAIL_TEXT_LABEL_COLOR];
[[cell detailTextLabel] setNumberOfLines:3];
}
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
dateString = [dateFormat stringFromDate:current_order.order.time];
NSString *str = AMLocalizedString(#"kStatusListDetailsToDay", #"");
textLabelString = [NSString stringWithFormat:#"%# - %#", str, dateString];
[cell.textLabel setText:textLabelString];
[cell.detailTextLabel setText:detailTextString];
[cell setBackgroundColor:[UIColor redColor]];
[cell.dateLabel setBackgroundColor:[UIColor clearColor]];
cell.accessoryType = UITableViewCellAccessoryNone;
return cell;
}
------------------ICStatusViewController.h file-----------START-------
// ICStatusViewController.h
#import <UIKit/UIKit.h>
#import "Status.h"
#import "StatusCell.h"
#import "StatusControllerDelegate.h"
#import "ICStatusDetailsController.h"
typedef void (^ICStatusViewControllerDoneCallbackBlock)(id userInfo);
typedef void (^ICStatusViewControllerCancelCallbackBlock)(void);
#interface ICStatusViewController : UIViewController <UITableViewDelegate, UITableViewDataSource, UIActionSheetDelegate, ICStatusDetailsControllerDelegate> {
id<Statuses> statusObjects;
NSString *no_statuses;
NSOperationQueue *queue;
NSTimer *statusTimer;
__unsafe_unretained id<StatusControllerDelegate> delegate;
UIColor *first_color;
UIColor *second_color;
IBOutlet __unsafe_unretained UITableView *myTableView;
IBOutlet __unsafe_unretained UILabel *no_statuses_label;
IBOutlet __unsafe_unretained UIImageView *no_status_background;
#private
ICStatusViewControllerDoneCallbackBlock _doneCallbackBlock;
ICStatusViewControllerCancelCallbackBlock _cancelCallbackBlock;
}
#property (nonatomic, unsafe_unretained) UITableView* myTableView;
#property (nonatomic, copy) NSString* no_statuses;
#property (nonatomic, unsafe_unretained) UILabel* no_statuses_label;
#property (nonatomic, unsafe_unretained) id <StatusControllerDelegate> delegate;
#property (nonatomic, copy) ICStatusViewControllerDoneCallbackBlock doneCallbackBlock;
#property (nonatomic, copy) ICStatusViewControllerCancelCallbackBlock cancelCallbackBlock;
- (id)initWithStatus;
#end
You can either set the tint color of the navigation bar OR use a IMAGE instead of navigation bar and hide the navigation bar, using:
navigationController.navigationBarHidden = YES;
You are not talking about a UITableView, but about the UINavigationBar on the top. I fixed your question to reflect that. Basically there are two ways to set its tintColor:
The easier option would be to use the appearance protocol (iOS 5 and later), as this will change every NavigationBar in the whole app:
[[UINavigationBar appearance] setTintColor:[UIColor yellowColor]];
Or you do it on every single UINavigationBar of every UINavigationController.
[navigationController.navigationBar setTintColor:[UIColor yellowColor]];
just add this line for set yellow color to navigationcontroller in viewDidLoad: method of ICStatusViewController class..
[self.navigationController.navigationBar setTintColor:[UIColor yellowColor]];
and also with image like bellow..
[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:#"yourImageName"] forBarMetrics:UIBarMetricsDefault];// write your image name like yellow image
i hope this help you...
What's your tableView's style? If tableView's style is UITableViewStyleGrouped, you can't change backgroundColor on iOS 6. Try to change tableView's backgroundView.
self.settingsTableView = [[UITableView alloc] initWithFrame:rect
style:UITableViewStyleGrouped];
UIView *view = [[UIView alloc] initWithFrame:settingsTableView.frame];
view.backgroundColor = [UIColor redColor];
settingsTableView.backgroundView = view;
I am slowly developing a custom button (while learning how to implement classes etc).
I have a ViewController, which imports a SuperButton.h (UIControl) and then creates an instance of the SuperButton. (This works, as proved by a NSLog.)
But I cannot get the method in SuperButton to display a Label.
I think this might have something to with the '.center' value or the 'addSubview' command?
I would really appreciate your help. Thanks.
Here is my SuperButton.m code:
#import "SuperButton.h"
#implementation SuperButton
#synthesize firstTitle;
#synthesize myLabel;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
- (void) shoutName{
NSLog(#"My name is %#", firstTitle);
self.backgroundColor = [UIColor blueColor];
CGRect labelFrame = CGRectMake(0.0f, 0.0f, 100.0f, 50.0f);
self.myLabel = [[UILabel alloc] initWithFrame:labelFrame];
self.myLabel.text = #"Come on, don't be shy.";
self.myLabel.font = [UIFont italicSystemFontOfSize:14.0f];
self.myLabel.textColor = [UIColor grayColor];
self.myLabel.center = self.center;
[self addSubview:self.myLabel];
}
Here is the code in my ViewController:
- (void) makeButton{
SuperButton *button1 = [[SuperButton alloc] init];
button1.firstTitle = #"Mr. Ploppy";
[button1 shoutName];
}
(EDIT:) Just in case, here's the SuperButton.h code:
#import <UIKit/UIKit.h>
#interface SuperButton : UIControl
#property (nonatomic, strong) NSString *firstTitle;
#property (nonatomic, strong) UILabel *myLabel;
- (void) shoutName;
#end
I found an answer elsewhere.
I needed to addSubview the 'button'. My working code now looks like this:
- (void) makeButton{
SuperButton *button1 = [[SuperButton alloc] init];
button1.firstTitle = #"Mr. Ploppy";
[button1 shoutName];
[self.view addSubview:button1.myLabel];
[self.view sendSubviewToBack:button1.myLabel];
}
You are initializing your button not with initWithFrame: method, but with simple init. This makes the button of CGRectZero size. Change this line:
SuperButton *button1 = [[SuperButton alloc] init];
to this:
SuperButton *button1 = [[SuperButton alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 100.0f, 50.0f)];
or add a call to setFrame: after initializing your button.
I am creating custom UITableViewCell before starting to create it i read many articles about it and I start to create my own CustomTableViewCell.
In my custom TableViewCell I have 4 filds:
UILabel* cellTitle
UILabel* cellDateTime
UIView* cellMainImage
UIImageView* arraow image
Here is how is my TableViewCell appear:
And here is the code: of CustomTableViewCell.h
#import <UIKit/UIKit.h>
#define TAGS_TITLE_SIZE 20.0f
#define TITLE_LABEL_TAG 1
#define DATA_TIME_LABEL_TAG 5
#define ARROW_IMAGE_TAG 6
#define MAIN_IMAGE_TAG 7
// Enumeration for initiakization TableView Cells
typedef enum {
NONE_TABLE_CELL = 0,
NEWS_FEED_TABLE_CELL = 1,
TAGS_TABLE_CELL = 2
}TableTypeEnumeration;
// Class for Custom Table View Cell.
#interface CustomTableViewCell : UITableViewCell {
// Title of the cell.
UILabel* cellTitle;
UILabel* cellDataTime;
UIView* cellMainImage;
UIImageView* cellArrowImage;
}
// Set the title of the cell.
- (void) SetCellTitle: (NSString*) _cellTitle;
- (void) SetCellDateTime: (NSString*) _cellDataTime;
- (void) ReleaseCellMainImage;
- (void) InitCellTitleLable;
- (void) InitCellDateTimeLabel;
- (void) InitCellMainImage;
// Init With Style (With additional parametr TableTypeEnumeration)
- (id)initWithStyle: (UITableViewCellStyle)style reuseIdentifier: (NSString *)reuseIdentifier tableType:(TableTypeEnumeration)tabletypeEnum;
#end
And here is the code of: CustomTableViewCell.m
#import "CustomTableViewCell.h"
#implementation CustomTableViewCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
return [self initWithStyle:style reuseIdentifier:reuseIdentifier tableType:NONE_TABLE_CELL];
}
- (id)initWithStyle: (UITableViewCellStyle)style reuseIdentifier: (NSString *)reuseIdentifier tableType:(TableTypeEnumeration)tabletypeEnum {
// Get Self.
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
// Switch table View Cells
switch(tabletypeEnum) {
case NEWS_FEED_TABLE_CELL: {
// Create Cell Title Text
cellTitle = [[UILabel alloc] initWithFrame:CGRectMake(75.0f, 2.5f, 180.0f, 33.0f)];
cellTitle.tag = TITLE_LABEL_TAG;
cellTitle.font = [UIFont boldSystemFontOfSize: 13.0f];
cellTitle.lineBreakMode = UILineBreakModeWordWrap;
cellTitle.numberOfLines = 0;
cellTitle.textAlignment = UITextAlignmentLeft;
cellTitle.textColor = [UIColor blackColor];
[self.contentView addSubview:cellTitle];
[cellTitle release];
// Create Cell Description Text.
cellDataTime = [[UILabel alloc] initWithFrame:CGRectMake(135.0f, 38.0f, 100.0f, 15.0f)];
cellDataTime.tag = DATA_TIME_LABEL_TAG;
cellDataTime.font = [UIFont italicSystemFontOfSize: 12.0f];
cellDataTime.textAlignment = UITextAlignmentLeft;
cellDataTime.textColor = [UIColor blackColor];
cellDataTime.lineBreakMode = UILineBreakModeWordWrap;
[self.contentView addSubview:cellDataTime];
[cellDataTime release];
// Create Cell Arrow Image.
cellArrowImage = [[UIImageView alloc] initWithFrame:CGRectMake(260.0f, 7.0f, 40.0f, 49.0f)];
cellArrowImage.tag = ARROW_IMAGE_TAG;
cellArrowImage.backgroundColor = [UIColor whiteColor];
cellArrowImage.image = [UIImage imageNamed:#"Grey Arrow.png"];;
[self.contentView addSubview:cellArrowImage];
[cellArrowImage release];
// Create Cell Main Image.
cellMainImage = [[[UIView alloc] initWithFrame:CGRectMake(2.0f, 2.5f, 55.0f, 50.0f)] autorelease];
cellMainImage.tag = MAIN_IMAGE_TAG;
[self.contentView addSubview:cellMainImage];
break;
}
case TAGS_TABLE_CELL: {
// Create and initialize Title of Custom Cell.
cellTitle = [[UILabel alloc] initWithFrame:CGRectMake(10, (44 - TAGS_TITLE_SIZE)/2, 260, 21)];
cellTitle.backgroundColor = [UIColor clearColor];
cellTitle.opaque = NO;
cellTitle.textColor = [UIColor blackColor];
cellTitle.highlightedTextColor = [UIColor whiteColor];
cellTitle.font = [UIFont boldSystemFontOfSize:TAGS_TITLE_SIZE];
cellTitle.textAlignment = UITextAlignmentLeft;
[self.contentView addSubview:cellTitle];
[cellTitle release];
break;
}
default: break;
}
}
return self;
}
- (void) ReleaseCellMainImage {
[cellMainImage release];
}
- (void) InitCellTitleLable {
cellTitle = (UILabel *)[self.contentView viewWithTag:TITLE_LABEL_TAG];
}
- (void) InitCellDateTimeLabel {
cellDataTime = (UILabel *)[self.contentView viewWithTag:DATA_TIME_LABEL_TAG];
}
- (void) InitCellMainImage {
//UIView* oldImage = [self.contentView viewWithTag:MAIN_IMAGE_TAG];
//[oldImage removeFromSuperview];
}
- (void) SetCellTitle: (NSString*) _cellTitle {
cellTitle.text = _cellTitle;
}
- (void) SetCellDateTime: (NSString*) _cellDataTime {
cellDataTime.text = _cellDataTime;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
}
- (void)dealloc {
// Call base delloc
[super dealloc];
}
#end
Now when I use my CustomTableViewCell in the code of the program the memory of my iphone always go up !!! Every time when I open tableView the memory grows for 2mb and when I open and close tableView for 10times it become more then 30mb !!! Whot can I do ???
And one more question
How I can get the event when user for example press on my image in custom cell ???
In addition to considering cell reuse as others say, if the memory use goes up with each open, you may have a memory leak. Perhaps the view you have that creates the table is not releasing it when deallocated.
You aren't reusing your cells. Hence a new cell is created everytime you scroll.
In your delegate you need to recreate cell as follows:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (nil == cell) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier] autorelease];
}
return cell;
Are you implementing cell re-use when creating the cell? There is no indication in the code that you attempt to dequeue a reusable cell from UITableView prior to the init, though this may be in the table view itself. As can be seen in Praveens post, there is an attempt to dequeue a cell, and only if this returns nil is the cell being initialised.
As a result, you may be creating a new cell object every time this particular cell comes into view. Is cell reuse adopted in the table view?
What code is in the tableview delegate method - tableView:cellForRowAtIndexPath?
I have a tableView:didSelectRowAtIndexPath: where I create a ViewController-Instance each time an item is selected. Sometimes it works fine for a long time, sometimes it crashes with a EXC_BAD_ACCESS very quickly. The debugger blames the line [super dealloc]; in the QuestionDetailViewController.
Why? I log the QuestionDetailViewController retainCount. That looks fine.
QuestionDetailViewController
#import <UIKit/UIKit.h>
#import "Question.h"
#import "Answer.h"
#interface QuestionDetailViewController : UIViewController < UIScrollViewDelegate , QuestionDetailViewProtocol> {
Question *question;
UILabel *answerText;
UILabel *titleLabel;
}
#property(nonatomic,retain) Question *question;
#property(nonatomic,retain) UILabel *answerText;
#property(nonatomic,retain) UILabel *titleLabel;
#end
#import "QuestionDetailViewController.h"
#implementation QuestionDetailViewController
#synthesize question;
#synthesize answerText;
#synthesize titleLabel;
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)viewWillAppear:(BOOL)animated {
UIColor *bgColor = [UIColor colorWithRed:199.0/255 green:234.0/255 blue:251.0/255 alpha:1];
self.answerText = (UILabel *)[self.view viewWithTag:2];
self.answerText.backgroundColor = bgColor;
self.answerText.text = self.question.answer.text;
self.titleLabel = (UILabel*)[self.view viewWithTag:1];
CGSize sizeTitle = [self.question.title sizeWithFont:[titleLabel font]
constrainedToSize:CGSizeMake(280.0, INFINITY)
lineBreakMode:UILineBreakModeWordWrap];
self.titleLabel.text = self.question.title;
self.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
self.titleLabel.frame = CGRectMake(10,10, 260, sizeTitle.height);
CGSize sizeText = [self.question.answer.text sizeWithFont:[self.answerText font]
constrainedToSize:CGSizeMake(280.0, INFINITY)
lineBreakMode:UILineBreakModeWordWrap];
self.answerText.frame = CGRectMake(0,20+sizeTitle.height, 310, sizeText.height+sizeTitle.height);
[(UIScrollView *)self.view setContentSize:CGSizeMake(280, answerText.frame.size.height +sizeTitle.height)];
self.view.backgroundColor = bgColor;
[super viewWillAppear:animated];
}
- (void)viewDidDisappear:(BOOL)animated {
NSLog(#"%d", [self retainCount]);
[super viewDidDisappear:animated];
[self release];
}
-(IBAction)goBack:(id)sender{
[self.navigationController popViewControllerAnimated:YES];
}
- (void)dealloc {
NSLog(#"QDC dealoc");
[self.answerText release];
[self.titleLabel release];
[self.question release];
[super dealloc];
}
#end
tableView:didSelectRowAtIndexPath:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
QuestionDetailViewController *qdc = [[QuestionDetailViewController alloc] initWithNibName:#"QuestionDetailViewController" bundle:nil];
Question* question;
if ([filteredQuestions count]>0) {
question = [self.filteredQuestions objectAtIndex:indexPath.row];
} else {
question = [self.questions objectAtIndex:indexPath.row];
}
[qdc setQuestion:question];
[question release];
NSLog(#"%d", [qdc retainCount]);
[self.navigationController pushViewController:qdc animated:YES];
[qdc release];
}
This:
- (void)viewDidDisappear:(BOOL)animated {
NSLog(#"%d", [self retainCount]);
[super viewDidDisappear:animated];
[self release];
}
looks incredibly suspicious. Did you do [self retain]? If not, then why are you releasing? If you are, you're probably doing something wrong, because [self retain] is an incredibly rare thing to need to do.
Instead of:
[self.answerText release];
[self.titleLabel release];
[self.question release];
use:
self.answerText = nil;
self.titleLabel = nil;
self.question = nil;
or:
[answerText release]; answerText = nil;
[titleLabel release]; titleLabel = nil;
[question release]; question = nil;