Popping View crashes Application at [super dealloc] - iphone

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;

Related

Why is my loaded nib crashing when memory is released?

If I run Build and Analyze this loads without errors according to the Analyzer but the app crashes. If I remove the [myStates release]; analyzer complains about possible leak but the nib loads and runs just fine. MyStateList is a nib which has a pickerview inside that loads a plist if this helps. Please help.
Main TrialViewControllerViewController Implementation File
#import "TrialViewControllerViewController.h"
#import "MyStateList.h"
#implementation TrialViewControllerViewController
- (void)viewDidLoad {
[super viewDidLoad];
MyStateList *myStates = [[MyStateList alloc] initWithNibName:#"MyStateList" bundle:nil];
[self.view addSubview:[myStates view]];
//[myStates release];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload {
}
- (void)dealloc {
[super dealloc];
}
#end
Here is what i am trying to load
MyStateList.h
#import <UIKit/UIKit.h>
#interface MyStateList : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource> {
UIPickerView *pickerView;
NSMutableArray *statesArray; // Written array
NSDictionary *stateListDictionary,*stateListDictionaries;
NSArray *firstDisplayArray,*updateDisplayArray,*switchDisplayArray;
NSInteger dTag;
NSString *nott,*verify,*notes;
IBOutlet UILabel *labelOne,*labelTwo,*labelThree,*labelName;
}
#property (nonatomic, retain) UIPickerView *pickerView;
#property (nonatomic, retain) NSDictionary *stateListDictionary,*stateListDictionaries;
#property (nonatomic, retain) NSArray *firstDisplayArray,*updateDisplayArray,*switchDisplayArray;
#property (nonatomic, retain) IBOutlet UILabel *labelOne,*labelTwo,*labelThree,*labelName;
#property (nonatomic, retain) NSString *nott,*verify,*notes;
- (void)loadData;
- (void)placeData;
- (void)createPicker;
#end
MyStateList.m
#import "MyStateList.h"
#implementation MyStateList
#synthesize pickerView;
#synthesize stateListDictionary,stateListDictionaries,firstDisplayArray,updateDisplayArray,switchDisplayArray ;
#synthesize labelOne,labelTwo,labelThree,labelName;
#synthesize nott,verify,notes;
- (void)viewDidLoad
{
[super viewDidLoad];
[self createPicker];
}
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
return 1;
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return [statesArray count];
}
-(UIView *)pickerView:(UIPickerView *)pickerViewCust viewForRow:(NSInteger)row forComponent: (NSInteger)component reusingView:(UIView *)view
{
NSString *rowItem = [statesArray objectAtIndex: row];
UILabel *lblRow = [[[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, [pickerViewCust bounds].size.width, 44.0f)]autorelease];
[lblRow setTextAlignment:UITextAlignmentCenter];
[lblRow setTextColor: [UIColor blueColor]];
[lblRow setText:rowItem];
[lblRow setBackgroundColor:[UIColor clearColor]];
return lblRow;
}
- (void)createPicker
{
NSString *path = [[NSBundle mainBundle] pathForResource:
#"StateArray" ofType:#"plist"];
stateListDictionary = [NSDictionary dictionaryWithContentsOfFile:path];
labelName.text = [NSString stringWithFormat:#"Arizona"];
[self loadData];
float screenWidth = [UIScreen mainScreen].bounds.size.width;
float pickerWidth = screenWidth * 1 / 2;
float xPoint = screenWidth / 2 - pickerWidth / 1;
pickerView = [[UIPickerView alloc] init];
[pickerView setDataSource: self];
[pickerView setDelegate: self];
[pickerView setFrame: CGRectMake(xPoint, 280.0f, pickerWidth, 180.0f)];
pickerView.showsSelectionIndicator = YES;
[pickerView selectRow:2 inComponent:0 animated:YES];
[self.view addSubview: pickerView];
}
- (void)loadData
{
firstDisplayArray = [stateListDictionary objectForKey:#"Arizona"];
dTag = 1;
[self placeData];
stateListDictionary = nil; // kill the list
statesArray = [[NSMutableArray alloc] init];
[statesArray addObject:#"Alabama"];
[statesArray addObject:#"Alaska"];
[statesArray addObject:#"Arizona"];
[statesArray addObject:#"Arkansas"];
[statesArray addObject:#"California"];
}
- (void)placeData
{
if (dTag == 1)
{
switchDisplayArray = firstDisplayArray;
dTag = 0;
} else {
switchDisplayArray = updateDisplayArray;
}
nott = [switchDisplayArray objectAtIndex:0];
verify = [switchDisplayArray objectAtIndex:1];
notes = [switchDisplayArray objectAtIndex:2];
labelOne.text = nott;
labelTwo.text = verify;
labelThree.text = notes;
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent: (NSInteger)component
{
NSString *path = [[NSBundle mainBundle] pathForResource:
#"StateArray" ofType:#"plist"];
stateListDictionaries = [NSDictionary dictionaryWithContentsOfFile:path];
labelName.text = [statesArray objectAtIndex: row];
updateDisplayArray = [stateListDictionaries objectForKey:labelName.text];
[self placeData];
}
- (void)dealloc
{
[pickerView release];
[stateListDictionary release];
[stateListDictionaries release];
[statesArray release];
[super dealloc];
}
#end
If I had to guess, MyStatesList is a subclass of UIViewController.
If you release myStates at the end of the block, you're essentially removing the brain from your view controller, but leaving its body there. You need to keep the controller itself around as well as the view, as the view is owned by the controller. Not the other way around.
The view from your view controller is retained by the view, but you killed the view controller itself. The bigger problem is you CAN'T just add views from UIViewControllers in this manner. On iOS5 you have the ability to use addChildViewController: and prior to that you can use one of the provided container controllers.
You do indeed need to release your MyStateList object.
Here's what's happening:
You initialize a new MyStateList, which has a retain count of 1
You add a subview to your view, and that subview is NOT the MyStateList object, but the ivar view of your MyStateList object.
When you don't release your myStates object, you are indeed leaking this object, since nothing has a reference to this object anymore, and the memory was never deallocated. (Its retain count never reached 0.)
That having been said, what kind of error occurs when your application crashes? I'm guessing that MyStateList is a UIViewController, and the view is then attempting to access/communicate with its parent, which has been released/deallocated.
In your -(void)dealloc; you are calling [super dealloc] first, this is wrong. Make it the last call in the method. This should fix your crash.
- (void)dealloc
{
// Wrong Way
[super dealloc];
[pickerView release];
[stateListDictionary release];
[stateListDictionaries release];
[statesArray release];
}
`
- (void)dealloc
{
// Right way
[pickerView release];
[stateListDictionary release];
[stateListDictionaries release];
[statesArray release];
[super dealloc];
}
you add the view [myStates view], to the controller's view, so the view is hold by the controller's view.
then you release "myStates" for avoid memeory leak, it is removed.
and I guess in your view [myStates view], there must be some delegates related to the object "myState", but it was removed just before. So, the app crash.
To avoid both problems, memory leak and crash. I think you should make the "myStates" hold by your controller as a member variable. And you could release "myState" when your viewUnloaded.

Can not get UITableView to Display NSArray

Sounds like a question that has been answered... maybe but i have checked all of the possible solutions i believe and nothing will work for me.
My .h file looks like this
#import <UIKit/UIKit.h>
#interface epsMenuPage : UIViewController<UITableViewDelegate,UITableViewDataSource>{
NSArray *listData;
...
UITableView *menuList;
...
}
#property (nonatomic,retain) NSArray *listData;
...
#property (nonatomic, retain) IBOutlet UITableView *menuList;
...
#end
My .m file looks like this
#implementation epsMenuPage
#synthesize listData;
...
#synthesize menuList;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
//Arrays credit,debit and both
creditListData = [[NSArray alloc]initWithObjects:#"Return",#"Force Sale",#"Authorize Only",#"Total Sales",#"Items Sold",#"Reciept's", nil];
debitListData = [[NSArray alloc]initWithObjects:#"Return",#"Force Sale",#"Authorize Only",#"Total Sales",#"Items Sold",#"Reciept's", nil];
bothListData = [[NSArray alloc]initWithObjects:#"Batch History",#"Settle Batch", nil];
self.listData = creditListData;
[menuList reloadData];
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
self.view.backgroundColor =[UIColor colorWithRed:255/255.0 green:95/255.0 blue:95/255.0 alpha:1.0];
[colorChange setBackgroundColor:[UIColor colorWithRed:255/255.0 green:95/255.0 blue:95/255.0 alpha:1.0]];
[self.view addSubview:creditTabButton];
[self.view addSubview:debitTabButton];
[self.view addSubview:bothTabButton];
[self.view addSubview:creditButtonText];
[self.view addSubview:debitButtonText];
[self.view addSubview:bothBottonText];
[self.view addSubview:colorChange];
}
- (void)viewDidUnload
{
[self setTitleBAckButton:nil];
[self setTitleSettingsButton:nil];
[self setCreditTabButton:nil];
[self setDebitTabButton:nil];
[self setBothTabButton:nil];
[self setMenuList:nil];
[self setColorChange:nil];
[self setCreditButtonText:nil];
[self setDebitButtonText:nil];
[self setBothBottonText:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.listData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *SimpleTableIdentifier = #"tableID";
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:SimpleTableIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:SimpleTableIdentifier] autorelease];
}
NSUInteger row = [indexPath row];
cell.textLabel.text = [self.listData objectAtIndex:row];
return cell;
}
- (void)dealloc {
[titleBAckButton release];
[titleSettingsButton release];
[creditTabButton release];
[debitTabButton release];
[bothTabButton release];
[menuList release];
[colorChange release];
[creditButtonText release];
[debitButtonText release];
[bothBottonText release];
[listData release];
[super dealloc];
}
- (IBAction)titleBackClick:(id)sender {
[self.parentViewController dismissModalViewControllerAnimated:YES];
}
- (IBAction)titleSettingsClick:(id)sender {
}
- (IBAction)creditTabClick:(id)sender {
self.listData = creditListData;
[menuList reloadData];
[colorChange setBackgroundColor:[UIColor colorWithRed:255/255.0 green:95/255.0 blue:95/255.0 alpha:1.0]];
[self.view addSubview:creditTabButton];
[self.view addSubview:creditButtonText];
[self.view addSubview:colorChange];
self.view.backgroundColor = [UIColor colorWithRed:255/255.0 green:95/255.0 blue:95/255.0 alpha:1.0];
}
- (IBAction)debitTabClick:(id)sender {
self.listData = debitListData;
[menuList reloadData];
[colorChange setBackgroundColor:[UIColor colorWithRed:244/255.0 green:133/255.0 blue:33/255.0 alpha:1.0]];
[self.view addSubview:debitTabButton];
[self.view addSubview:debitButtonText];
[self.view addSubview:colorChange];
self.view.backgroundColor = [UIColor colorWithRed:244/255.0 green:133/255.0 blue:33/255.0 alpha:1.0];
}
- (IBAction)bothTabClick:(id)sender {
self.listData = bothListData;
[menuList reloadData];
[colorChange setBackgroundColor:[UIColor colorWithRed:72/255.0 green:72/255.0 blue:255/255.0 alpha:1.0]];
[self.view addSubview:bothTabButton];
[self.view addSubview:bothBottonText];
[self.view addSubview:colorChange];
self.view.backgroundColor = [UIColor colorWithRed:72/255.0 green:72/255.0 blue:255/255.0 alpha:1.0];
}
#end
I really for the life of me can not figure out why it wont display to my TableView, i have tried so many different tutorials.
any help is greatly appreciated.
You're never adding the menuList table view to your view. Add it and see if that does the trick:
// In -viewDidLoad
[self.view addSubview:menuList];
EDIT 1: Did you declare properties in your .h? These aren't visible, so it appears as if you're not creating or adding your table view to the view controller's view. However, if you are using IBOutlets, then this probably isn't the issue.
EDIT 2: From the comments below, your dataSource is nil, which is exactly why nothing is being displayed. Make sure your table view in Interface Builder has its dataSource outlet pointing to your view controller. To be double sure, delete the table view from Interface Builder and add it back again. Make sure your connections are exactly right. Also try cleaning the project and rebuilding, as well as restarting Xcode.
It looks like you are missing the required datasource method:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView; {
return 1;
}
Also, it looks like you are not actually initializing your UIButton's, or anything you are adding as a subview. Are you using a nib?

App crashes on releasing custom Table Cell

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

memory leak with navBar

Can you help me please to fix the memory leak ?
#import <Foundation/Foundation.h>
#interface NavBar : NSObject
{
NSString* nav;
}
#property (nonatomic, retain) NSString* nav;
+ (NavBar *) sharedInstance;
#end
#import "NavBar.h"
#implementation NavBar
#synthesize nav;
-(void)dealloc
{
[nav release];
}
+(NavBar *)sharedInstance
{
static NavBar *myInstance = nil;
if (nil == myInstance) {
myInstance = [[[self class] alloc] init];
}
return myInstance;
}
#end
i have a leak here :
- (void) viewWillAppear:(BOOL)animated
{
[NavBar sharedInstance].nav = #"navBar.png";
self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
self.navigationController.navigationBar.tintColor = [UIColor clearColor];
self.navigationController.navigationBar.barStyle = UIBarStyleDefault;
self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:19/255.0 green:140/255.0 blue:130/255.0 alpha:1.0];
[super viewWillAppear:animated];
}
in the delegate of my app:
#interface UINavigationBar (CustomBackground)
- (void)drawRectCustomBackground:(CGRect)rect;
#end
#implementation UINavigationBar (CustomBackground)
- (void)drawRectCustomBackground:(CGRect)rect
{
if (self.barStyle == UIBarStyleDefault)
{
UIImage *image = [UIImage imageNamed:[NavBarStyles sharedInstance].navStyle];
[image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
return;
}
[self drawRectCustomBackground:rect];
}
At some point, you need to call
[[NavBar sharedInstance] release];
or an equivalent. Probably right before you exit.

Scroll View in Grid TableView

I'm completely new to iPhone development. I have a query regarding how to implement scroll view in table view. I'm using following code
#import <UIKit/UIKit.h>
#class ScrollViewViewController;
#interface ScrollViewAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
ScrollViewViewController *viewController;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) IBOutlet ScrollViewViewController *viewController;
#end
////////////////////////////////////////////
#import "ScrollViewAppDelegate.h"
#import "ScrollViewViewController.h"
#implementation ScrollViewAppDelegate
#synthesize window;
#synthesize viewController;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Override point for customization after app launch
[window addSubview:viewController.view];
[window makeKeyAndVisible];
}
- (void)dealloc {
[viewController release];
[window release];
[super dealloc];
}
#end
///////////////////////////
#import <UIKit/UIKit.h>
#interface MyTableCell : UITableViewCell {
NSMutableArray *columns;
}
- (void)addColumn:(CGFloat)position;
#end
//////////////////////////
#import "MyTableCell.h"
#implementation MyTableCell
- (id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
if (self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) {
// Initialization code
columns = [NSMutableArray arrayWithCapacity:5];
[columns retain];
}
return self;
}
- (void)addColumn:(CGFloat)position {
[columns addObject:[NSNumber numberWithFloat:position]];
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (void)drawRect:(CGRect)rect {
CGContextRef ctx = UIGraphicsGetCurrentContext();
// just match the color and size of the horizontal line
CGContextSetRGBStrokeColor(ctx, 0.5, 0.5, 0.5, 1.0);
CGContextSetLineWidth(ctx, 0.25);
for (int i = 0; i < [columns count]; i++) {
// get the position for the vertical line
CGFloat f = [((NSNumber*) [columns objectAtIndex:i]) floatValue];
CGContextMoveToPoint(ctx, f, 0);
CGContextAddLineToPoint(ctx, f, self.bounds.size.height);
}
CGContextStrokePath(ctx);
[super drawRect:rect];
}
- (void)dealloc {
[super dealloc];
[columns dealloc];
}
#end
//////////////////////
#import <UIKit/UIKit.h>
#interface RootViewController : UITableViewController {
}
#end
/////////////////
#import "RootViewController.h"
#import "MyTableCell.h"
#implementation RootViewController
#define LABEL_TAG 1
#define VALUE_TAG 2
#define FIRST_CELL_IDENTIFIER #"TrailItemCell"
#define SECOND_CELL_IDENTIFIER #"RegularCell"
- (void)viewDidLoad {
// Add the following line if you want the list to be editable
// self.navigationItem.leftBarButtonItem = self.editButtonItem;
self.title = #"Grids!";
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
return 19;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *MyIdentifier = [NSString stringWithFormat:#"MyIdentifier %i", indexPath.row];
MyTableCell *cell = (MyTableCell *)[tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[[MyTableCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
UILabel *label = [[[UILabel alloc] initWithFrame:CGRectMake(0.0, 0, 30.0,
tableView.rowHeight)] autorelease];
[cell addColumn:40];
label.tag = LABEL_TAG;
label.font = [UIFont systemFontOfSize:12.0];
label.text =#"S.NO";// [NSString stringWithFormat:#"%d", indexPath.row];
label.textAlignment = UITextAlignmentRight;
label.textColor = [UIColor redColor];
label.autoresizingMask = UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:label];
label = [[[UILabel alloc] initWithFrame:CGRectMake(40.0, 0, 70.0,
tableView.rowHeight)] autorelease];
[cell addColumn:120];
label.tag = VALUE_TAG;
label.font = [UIFont systemFontOfSize:12.0];
// add some silly value
label.text =#"Product ID";// [NSString stringWithFormat:#"%d", indexPath.row * 4];
label.textAlignment = UITextAlignmentRight;
label.textColor = [UIColor blueColor];
label.autoresizingMask = UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:label];
label = [[[UILabel alloc] initWithFrame:CGRectMake(134.0, 0, 70.0,
tableView.rowHeight)] autorelease];
[cell addColumn:220];
label.tag = VALUE_TAG;
label.font = [UIFont systemFontOfSize:12.0];
// add some silly value
label.text =#"Product Name";// [NSString stringWithFormat:#"%d", indexPath.row * 4];
label.textAlignment = UITextAlignmentRight;
label.textColor = [UIColor greenColor];
label.autoresizingMask = UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:label];
label = [[[UILabel alloc] initWithFrame:CGRectMake(230.0, 0, 70.0,
tableView.rowHeight)] autorelease];
[cell addColumn:310];
label.tag = VALUE_TAG;
label.font = [UIFont systemFontOfSize:12.0];
// add some silly value
label.text =#"Customer Name";// [NSString stringWithFormat:#"%d", indexPath.row * 4];
label.textAlignment = UITextAlignmentRight;
label.textColor = [UIColor greenColor];
label.autoresizingMask = UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:label];
label = [[[UILabel alloc] initWithFrame:CGRectMake(320.0, 0, 70.0,
tableView.rowHeight)] autorelease];
[cell addColumn:400];
label.tag = VALUE_TAG;
label.font = [UIFont systemFontOfSize:12.0];
// add some silly value
label.text =#"Customer Product";// [NSString stringWithFormat:#"%d", indexPath.row * 4];
label.textAlignment = UITextAlignmentRight;
label.textColor = [UIColor greenColor];
label.autoresizingMask = UIViewAutoresizingFlexibleRightMargin |
UIViewAutoresizingFlexibleHeight;
[cell.contentView addSubview:label];
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated {
}
- (void)viewDidDisappear:(BOOL)animated {
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
// Release anything that's not essential, such as cached data
}
- (void)dealloc {
[super dealloc];
}
#end
////////////
#import <UIKit/UIKit.h>
#interface ScrollViewViewController : UIViewController<UIScrollViewDelegate> {
}
#end
/////////////
#import "ScrollViewViewController.h"
#import "RootViewController.h"
#implementation ScrollViewViewController
/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
// Custom initialization
}
return self;
}
*/
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
RootViewController *RootViewControllerLink = [[RootViewController alloc]initWithNibName:#"RootViewController" bundle:nil];
RootViewControllerLink.view.tag = 100;
/* UIImageView *imgView = [[[UIImageView alloc] initWithImage:
[UIImage imageNamed:#"winkler-gnu-blue.png"]] autorelease];
imgView.tag = 100;
*/
UIScrollView *scrollView = [[[UIScrollView alloc]
initWithFrame:CGRectMake(0,0,320,480)] autorelease];
scrollView.delegate = self;
scrollView.minimumZoomScale = 0.25;
scrollView.maximumZoomScale = 2;
scrollView.bounces = NO;
scrollView.showsHorizontalScrollIndicator = NO;
scrollView.showsVerticalScrollIndicator = NO;
scrollView.contentSize = RootViewControllerLink.view.frame.size;
scrollView.contentOffset =
CGPointMake((RootViewControllerLink.view.frame.size.width-320)/2,
(RootViewControllerLink.view.frame.size.height-480)/2);
[scrollView addSubview:RootViewControllerLink.view];
self.view = scrollView;
}
/*- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
return [self.view viewWithTag:100];
}
- (BOOL)touchesShouldBegin:(NSSet *)touches withEvent:(UIEvent *)event inContentView:(UIView *)view
{
return YES;
}// default returns YES
- (BOOL)touchesShouldCancelInContentView:(UIView *)view
{
return YES;
}
*/
// not called if canCancelContentTouches is NO. default returns YES if view isn't UIControl
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
#end
In above code if I set scroll for UIIMage then it works but if I set scroll view for RootViewController then it doesn't work.
I didn't read your code, please reformat it so others can read it easily.
What do you mean by a UIScrollView in an UITableView? Inside the cells? Still I don't get it.
FYI UITableView inherits from UIScrollView ...
What functionality do you exactly want to achieve?
I will recommend to read some of the samples given by Apple. There are very good and extensive examples specially regarding UIKit.