Delay introduced while presenting UIViewController - ios

I am developing application in which I am presenting new UIViewController from another using [self performSegueWithIdentifier:#"newViewSegue" sender:self];
In new UIViewController I am initialising my view elements and adding UITableView programmatically to it.
But when I call this performSegueWithIdentifier new UIViewController is displayed after some delay, I tried to put log in viewDidLoad of new UIViewController and before [self performSegueWithIdentifier:#"newViewSegue" sender:self]; statement both statements are executed immediately but view is displayed after some interval.
My ViewDidLoad method is as follow:
-(void)viewDidLoad{
sharedObject=[SingleToneClass sharedManager];
selectedButtonTag=-1;
initFlag=0;
NSLog(#"End %#",[NSDate date]);
backgroundView.backgroundColor=[self hexToUiColor:#"E7E7E7"];
[mondayDateButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//set colour for all 7days buttons
[mondayDateButton.titleLabel setFont:[UIFont boldSystemFontOfSize:14]];
//Set font for all days button
[mondayButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//set title colour
[mondayButton.titleLabel setFont:[UIFont systemFontOfSize:12]];
//set font
//Changing image Color
//Home Button
[homeButton.titleLabel setFont:[UIFont fontWithName:kFontAwesomeFamilyName size:40]];
[homeButton setTitleColor:[self hexToUiColor:sharedObject.secondaryHexColorCode] forState:UIControlStateNormal];
[homeButton setTitle:[NSString fontAwesomeIconStringForIconIdentifier:#"fa-home"] forState:UIControlStateNormal];
//Back Button
[backButton.titleLabel setFont:[UIFont fontWithName:kFontAwesomeFamilyName size:27]];
[backButton setTitleColor:[self hexToUiColor:sharedObject.secondaryHexColorCode] forState:UIControlStateNormal];
[backButton setTitle:[NSString fontAwesomeIconStringForIconIdentifier:#"fa-chevron-left"] forState:UIControlStateNormal];
//Next Week Button
[nextWeek.titleLabel setFont:[UIFont fontWithName:kFontAwesomeFamilyName size:20]];
[nextWeek setTitleColor:[self hexToUiColor:sharedObject.secondaryHexColorCode] forState:UIControlStateNormal];
[nextWeek setTitle:[NSString fontAwesomeIconStringForIconIdentifier:#"fa-chevron-right"] forState:UIControlStateNormal];
//Previous Week Button
[previousWeek.titleLabel setFont:[UIFont fontWithName:kFontAwesomeFamilyName size:20]];
[previousWeek setTitleColor:[self hexToUiColor:sharedObject.secondaryHexColorCode] forState:UIControlStateNormal];
[previousWeek setTitle:[NSString fontAwesomeIconStringForIconIdentifier:#"fa-chevron-left"] forState:UIControlStateNormal];
[separatorLineView setBackgroundColor:[self hexToUiColor:#"6D6D6D"]];
[selectLabel setTextColor:[self hexToUiColor:#"6D6D6D"]];
[selectLabel setFont:[UIFont boldSystemFontOfSize:13]];
selectLabel.text=[NSString stringWithFormat:#"%#",selectedTitle];
sharedObject.bookADateTitle=selectedTitle;
//make Buttons Rounded
mondayDateButton.clipsToBounds = YES;
mondayDateButton.layer.cornerRadius = mondayDateButton.frame.size.height/2;
NSDate *currentDate;
if (sharedObject.bookDateViewDate.length>0) {
NSDateFormatter *dateFormat1 = [[NSDateFormatter alloc] init];
[dateFormat1 setDateFormat:#"yyyy-MM-dd"];
currentDate=[dateFormat1 dateFromString:sharedObject.bookDateViewDate];
}
else{
currentDate=[NSDate date];
}
[self setDate:currentDate];
[self setDateToLabel:currentDate]; //set formatted date
//create and initialise UITableView
static NSString *cellIdentifier=#"CustomHiddenViewCell";
CustomHiddenViewCell *cell = (CustomHiddenViewCell *)[slotsTableView dequeueReusableCellWithIdentifier:cellIdentifier];
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"CustomHiddenViewCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
double heightOfTable=(self.view.frame.size.height-backgroundView.frame.size.height);
//creating tableview1
slotsTableView=[[UITableView alloc]initWithFrame:CGRectMake(self.view.frame.origin.x,self.view.frame.origin.y+backgroundView.frame.size.height,self.view.frame.size.width,heightOfTable)];
slotsTableView.scrollEnabled=YES;
slotsTableView.delegate=self;
[slotsTableView flashScrollIndicators];
slotsTableView.dataSource=self;
slotsTableView.bounces=NO;
slotsTableView.showsVerticalScrollIndicator=YES;
slotsTableView.separatorStyle=UITableViewCellSeparatorStyleNone;
[self.view addSubview:slotsTableView];
//add swipe gesture
UISwipeGestureRecognizer *leftSwipRecognizer;
leftSwipRecognizer = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:#selector(SwipeRecognizer:)];
[leftSwipRecognizer setDirection:(UISwipeGestureRecognizerDirectionLeft)];
[slotsTableView addGestureRecognizer:leftSwipRecognizer];
UISwipeGestureRecognizer *rightSwipRecognizer;
rightSwipRecognizer = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:#selector(SwipeRecognizer:)];
[rightSwipRecognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
[slotsTableView addGestureRecognizer:rightSwipRecognizer];
[leftWeekRecognizer addTarget:self action:#selector(WeekSwipeRecognizer:)];
[leftWeekRecognizer setDirection:(UISwipeGestureRecognizerDirectionLeft)];
[rightWeekRecognizer addTarget:self action:#selector(WeekSwipeRecognizer:)];
[rightWeekRecognizer setDirection:(UISwipeGestureRecognizerDirectionRight)];
}
Can anyone tell me why this delay is introduced?

May be your code is executing in other then main thread, move your code in main thread or use GCD like
dispatch_async(dispatch_get_main_queue(), ^(void){
//Run UI Updates
});

Related

Issue with UIButton Title

I am fetching the data from UITableViewCell and am storing into string is countryString. I want to change the button title with country string but its not working, i thought it is a simple issue, but am struggling from last 2 hours. still I cant find the solution why is not working
countryButton=[[UIButton alloc]initWithFrame:CGRectMake(145, 145, 100, 30)];
countryButton.backgroundColor=[UIColor whiteColor];
[countryButton setTitle:CountryString forState:UIControlStateNormal];
countryButton.titleLabel.textColor=[UIColor blackColor];
[countryButton addTarget:self action:#selector(countryTable) forControlEvents:UIControlEventTouchUpInside];
[notesView addSubview:countryButton];
-(void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
jsonDict = [newarray objectAtIndex:indexPath.row];
CountryString=[jsonDict objectForKey:#"countryName"];
NSLog(#"country is %#", CountryString);
CountryTableview.hidden=YES;
}
try this
-(void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
jsonDict = [newarray objectAtIndex:indexPath.row];
CountryString=[jsonDict objectForKey:#"countryName"];
NSLog(#"country is %#", CountryString);
[countryButton setTitle:CountryString forState:UIControlStateNormal];
countryButton.titleLabel.textColor=[UIColor blackColor];
CountryTableview.hidden=YES;
}
assume that its your str
CountryString =#"XXXX";
UIButton *countryButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; //or button type custom
[countryButton addTarget:self action:#selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
[countryButton setFrame:CGRectMake(145, 145, 100, 30)];
[countryButton setTitle: CountryString forState:UIControlStateNormal];
[countryButton setExclusiveTouch:YES];
countryButton.backgroundColor=[UIColor whiteColor];
countryButton.titleLabel.textColor=[UIColor blackColor];
[self.view addSubview: countryButton]; //whatever u need self.view or notesView
-(void) buttonClicked:(UIButton*)sender
{
NSLog(#"you clicked on button %#", sender.tag);
}

IOS UITableview Scroll is not smooth in IOS6

And I complete IOS app in IOS 7 and its works fine IOS 7 and then I start converting my app to IOS 6 I face lot of problems.After a huge struggle I rectify almost all the issuse other that Performance issue
I am using UITableview to display all the contents and when I test my app in Iphone 5c there is no problem in scrolling the table view. And the I test my app in ipod retina list is not scrolling smoothly. It is one of the huge problem for me and also Its killing my time
To illustrate my issue I have added my tableview cell code below. Please Suggest me some quick solution
UITableviewCell Code
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellidentifier=#"cell";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellidentifier];
if (cell ==nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellidentifier]autorelease];
}
[[cell.contentView subviews] makeObjectsPerformSelector:#selector(removeFromSuperview)];
cell.selectionStyle = UITableViewCellEditingStyleNone;
UIView * contentview = [[[UIView alloc]init]autorelease];
UIImageView * userimage = [[[UIImageView alloc]init]autorelease];
UIImageView * itemimageview = [[[UIImageView alloc]init]autorelease];
UIView * bottomview = [[[UIView alloc]init]autorelease];
UILabel * imagenameLable = [[[UILabel alloc]init]autorelease];
UILabel * usernameLable = [[[UILabel alloc]init]autorelease];
UILabel * itemcostLable = [[[UILabel alloc]init]autorelease];
UIButton*fancybtn = [UIButton buttonWithType:UIButtonTypeCustom];
UIButton * addrditbtn = [UIButton buttonWithType:UIButtonTypeCustom];
UIButton * commentBtn = [UIButton buttonWithType:UIButtonTypeCustom];
UILabel * noofcommentsLable = [[[UILabel alloc]init]autorelease];
// [contentBgImageview setImage:[UIImage imageNamed:#"item_bg.png"]];
[itemimageview setAutoresizesSubviews:YES];
// [itemimageview setContentMode:UIViewContentModeScaleAspectFill];
[itemimageview setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#",[[[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"photos"]objectAtIndex:0]objectForKey:#"item_url_main_350"]]]];
[itemimageview setContentMode:UIViewContentModeScaleAspectFit];
[itemimageview setTag:indexPath.row];
[userimage setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#",[[[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"photos"]objectAtIndex:0]objectForKey:#"user_url_main_70"]]]];
[bottomview setBackgroundColor:[UIColor colorWithRed:200/255 green:54/255 blue:54/255 alpha:0.4]];
[bottomview setBackgroundColor:[UIColor colorWithRed:255 green:255 blue:255 alpha:1]];
// [bottomview setAlpha:0.5];
[imagenameLable setText:[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"item_title"]];
[imagenameLable setTextColor:[UIColor blackColor]];
[imagenameLable setFont:[UIFont fontWithName:#"Helvetica-Bold" size:14]];
[imagenameLable setBackgroundColor:[UIColor clearColor]];
[bottomview addSubview:imagenameLable];
[usernameLable setText:[NSString stringWithFormat:#"#%#",[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"sellername"]]];
[usernameLable setTextColor:[UIColor grayColor]];
[usernameLable setFont:[UIFont fontWithName:#"Helvetica" size:10]];
[usernameLable setBackgroundColor:[UIColor clearColor]];
[bottomview addSubview:usernameLable];
[itemcostLable setText:[NSString stringWithFormat:#"%# %#",delegate.currencyStr,[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"price"]]];
[itemcostLable setTextColor:[UIColor grayColor]];
[itemcostLable setFont:[UIFont fontWithName:#"Helvetica-Bold" size:16]];
[itemcostLable setBackgroundColor:[UIColor clearColor]];
[bottomview addSubview:itemcostLable];
// [addrditbtn setImage:[UIImage imageNamed:#"add.png"] forState:UIControlStateNormal];
if ([[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"liked"]isEqualToString:#"No"])
{
[fancybtn setImage:[UIImage imageNamed:#"fantacybtn.png"] forState:UIControlStateNormal];
[addrditbtn setImage:[UIImage imageNamed:#"addtolist.png"] forState:UIControlStateNormal];
}
else
{
[fancybtn setImage:[UIImage imageNamed:#"fantacydbtn.png"] forState:UIControlStateNormal];
[addrditbtn setImage:[UIImage imageNamed:#"addtolist.png"] forState:UIControlStateNormal];
}
NSString*itemid=[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"id"];
if ([delegate.fantacyitemsArray containsObject:itemid]) {
[fancybtn setImage:[UIImage imageNamed:#"fantacydbtn.png"] forState:UIControlStateNormal];
[addrditbtn setImage:[UIImage imageNamed:#"addtolist.png"] forState:UIControlStateNormal];
}
if ([delegate.unfantacyitemsArray containsObject:itemid]) {
[fancybtn setImage:[UIImage imageNamed:#"fantacybtn.png"] forState:UIControlStateNormal];
[addrditbtn setImage:[UIImage imageNamed:#"addtolist.png"] forState:UIControlStateNormal];
}
fancybtn.tag=[itemid intValue];
[fancybtn addTarget:self action:#selector(fancyBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
addrditbtn.tag=[itemid intValue];
[addrditbtn addTarget:self action:#selector(addtolistBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
[commentBtn setImage:[UIImage imageNamed:#"commentnew.png"] forState:UIControlStateNormal];
[commentBtn setUserInteractionEnabled:YES];
commentBtn.tag=indexPath.row;
[commentBtn addTarget:self action:#selector(commentBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
UIButton * usernameBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[usernameBtn setUserInteractionEnabled:YES];
usernameBtn.tag=indexPath.row;
[usernameBtn addTarget:self action:#selector(usernameBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
[noofcommentsLable setTextColor:[UIColor grayColor]];
[noofcommentsLable setFont:[UIFont fontWithName:#"Helvetica" size:12]];
int commentcount = 0;
if([delegate.newaddedcommentDict objectForKey:[NSString stringWithFormat:#"%#Array",[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"id"]]])
{
commentcount = [[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"commentcount"]intValue]+[[delegate.newaddedcommentDict objectForKey:[NSString stringWithFormat:#"%#Array",[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"id"]]]count];
}
else
{
commentcount = [[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"commentcount"]intValue];
}
[noofcommentsLable setText:[NSString stringWithFormat:#"%d",commentcount]];
UIScrollView * scroll = [[[UIScrollView alloc]init]autorelease];
// [scroll setScrollEnabled:NO];
[scroll setUserInteractionEnabled:YES];
UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(gestureAction:)];
[recognizer setNumberOfTapsRequired:1];
scroll.userInteractionEnabled = YES;
[scroll addGestureRecognizer:recognizer];
[itemcostLable setTextAlignment:NSTextAlignmentRight];
[bottomview setFrame:CGRectMake(0,3,300,37)];
[itemimageview setFrame:CGRectMake(0,0,300,240)];
CGSize size;
if ([[[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"photos"]objectAtIndex:0]objectForKey:#"width"]!=[NSNull null]||[[[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"photos"]objectAtIndex:0]objectForKey:#"height"]!=[NSNull null])
{
size= [self aspectScaledImageSizeForImageView:itemimageview width:[[[[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"photos"]objectAtIndex:0]objectForKey:#"width"]floatValue] height:[[[[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"photos"]objectAtIndex:0]objectForKey:#"height"]floatValue]];
}
else
{
size = CGSizeMake(100,100);
}
[itemimageview setFrame:CGRectMake((300-size.width)/2,0,size.width,size.height)];
[scroll setFrame:CGRectMake(0,43,300,size.height)];
//place holder image
UIImageView * placeholderimageview = [[[UIImageView alloc]init]autorelease];
[placeholderimageview setFrame:CGRectMake(130,0,40,size.height)];
[placeholderimageview setImage:[UIImage imageNamed:#"57.png"]];
[placeholderimageview setContentMode:UIViewContentModeScaleAspectFit];
// [itemimageview setBackgroundColor:[UIColor redColor]];
[imagenameLable setFrame:CGRectMake(40,5,160,15)];
[usernameLable setFrame:CGRectMake(40,20,160,15)];
[usernameBtn setFrame:CGRectMake(0,5,200,30)];
[itemcostLable setFrame:CGRectMake(220,0,70,40)];
[fancybtn setFrame:CGRectMake(5,size.height+48,78,25)];
[commentBtn setFrame:CGRectMake(221,size.height+48,40,25)];
[noofcommentsLable setFrame:CGRectMake(240,size.height+48,20,25)];
[addrditbtn setFrame:CGRectMake(265,size.height+48,27,25)];
// [commentBtn setFrame:CGRectMake(191,size.height+48,40,25)];
// [noofcommentsLable setFrame:CGRectMake(211,size.height+48,20,25)];
// [addrditbtn setFrame:CGRectMake(236,size.height+48,27,25)];
// [cartbtn setFrame:CGRectMake(268,size.height+48,27,25)];
[contentview setFrame:CGRectMake(10,5,300,size.height+78)];
[userimage setFrame:CGRectMake(5,5,30,30)];
[scroll setBackgroundColor:[UIColor colorWithRed:0.976 green:0.976 blue:0.976 alpha:1]];
[scroll setBackgroundColor:[UIColor clearColor]];
contentview.clipsToBounds = NO;
contentview.layer.masksToBounds = NO;
contentview.layer.shadowColor = [[UIColor grayColor] CGColor];
contentview.layer.shadowOffset = CGSizeMake(0,1);
contentview.layer.shadowOpacity = 0.2;
contentview.layer.shadowRadius = 0.6;
contentview.layer.cornerRadius = 6.0; // set as you want.
[bottomview setBackgroundColor:[UIColor clearColor]];
userimage.layer.cornerRadius = 15.0;
userimage.layer.masksToBounds = YES;
[itemimageview setUserInteractionEnabled:YES];
[scroll setBackgroundColor:[UIColor clearColor]];
[bottomview setBackgroundColor:[UIColor clearColor]];
[contentview setBackgroundColor:[UIColor whiteColor]];
//place holder image
[contentview addSubview:scroll];
[scroll addSubview:placeholderimageview];
[scroll addSubview:itemimageview];
[contentview addSubview:bottomview];
[contentview addSubview:fancybtn];
[contentview addSubview:addrditbtn];
[contentview addSubview:commentBtn];
[contentview addSubview:noofcommentsLable];
[contentview addSubview:userimage];
[contentview addSubview:usernameLable];
[contentview addSubview:usernameBtn];
[cell.contentView addSubview:contentview];
[cell setBackgroundColor:[UIColor clearColor]];
[cell.contentView setBackgroundColor:[UIColor clearColor]];
// Configure the cell...
return cell;
}
Its because in every time when cellForRowAtIndexPath: method called you recreating all subviews again.
You must do it only once.
Make a class that inherits from UITableViewCell.
//MyCell.h file
#interface MyCell : UITableViewCell
//here declare all views that you need, e.g.
#property (strong, nonatomic) UILabel *imagenameLable;
#property (strong, nonatomic) UILabel *usernameLable;
// and so on. But only those, that you mast set value (or read values) outside of this class.
// the other views declare in MyClass.m file, so they are for private use (eg. contentview,etc...)
#end
//MyCell.m file
#interface MyCell()
// here declare private properties
#property (strong, nonatomic) UIView* contentview;
// and so on...
#end
#implementation
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
[self setupUI];
}
return self;
}
- (void)setupUI
{
//and finally, in this method build your views, i.e. allocate your views, add subview of this cell, set frames, font to labels, text colors, etc...
//e.g.
self.contentview = [[[UIView alloc]init]autorelease];
self.contentview.clipsToBounds = NO;
self.contentview.layer.masksToBounds = NO;
self.contentview.layer.shadowColor = [[UIColor grayColor] CGColor];
self.contentview.layer.shadowOffset = CGSizeMake(0,1);
self.contentview.layer.shadowOpacity = 0.2;
self.contentview.layer.shadowRadius = 0.6;
self.contentview.layer.cornerRadius = 6.0; // set as you want.
// initialize other views
[self.contentview addSubview:self.scroll];
[self.scroll addSubview:self.placeholderimageview];
[self.scroll addSubview:self.itemimageview];
[self.contentview addSubview:self.bottomview];
[self.contentview addSubview:self.fancybtn];
[self.contentview addSubview:self.addrditbtn];
[self.contentview addSubview:self.commentBtn];
[self.contentview addSubview:self.noofcommentsLable];
[self.contentview addSubview:self.userimage];
[self.contentview addSubview:self.usernameLable];
[self.contentview addSubview:self.usernameBtn];
[self.contentView addSubview:self.contentview];
// something like this.
}
#end
And finally
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellidentifier=#"cell";
MyCell *cell=[tableView dequeueReusableCellWithIdentifier:cellidentifier];
if (cell ==nil)
{
cell = [[[MyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellidentifier]autorelease];
}
// here set values to properties of your cell. EG set text, change color if needed, change frame if needed, etc... But not remove and add them again!
cell.usernameLable.text = [NSString stringWithFormat:#"#%#",[[homePageArray objectAtIndex:indexPath.row]objectForKey:#"sellername"]]];
//etc...
return cell;
}
I found the solution for my code
This is because of
contentview.layer.shadowOffset = CGSizeMake(0,1);
contentview.layer.shadowOpacity = 0.2;
contentview.layer.shadowRadius = 0.6;
contentview.layer.cornerRadius = 6.0; // set as
Once I remove this line from my code Its works fine
There is lot of optimalization issues in your code. You should use Instruments with Time Profiler template to detect bottlenecks.
BTW, When you draw shadow of CALayer you should set CALayer's shadowPath property for outline of the shadow. This will speed up drawing your shadow much. Please refer documentation for more details.
dialogContainer.layer.shadowPath = [UIBezierPath bezierPathWithRoundedRect:dialogContainer.bounds cornerRadius:dialogContainer.layer.cornerRadius].CGPath;

CALayer memory leak

Hoping someone can help me here because I'm losing the will to live with this memory issue.
When I push a particular view controller, Instruments shows a growth of around 3MB with the majority coming from CALayer objects belonging to each control I have on the view controller (mostly textfields and labels).
When I pop this view controller these CALayer allocations remain in memory, in fact every time I push and pop the controller I get a growth of 3MB each time.
So my question is how do I remove these from memory, is there something I need to be doing when deallocating the controller? The only reference in my code to the controls' layer is to create rounded corners and a border width (layer.cornerRadius = 10) but I still get the growth even when I comment this out.
The controller contains a tableview where each cell contains 3 textfields, 2 buttons and an imageview which are created programatically.
-(UIButton*) formatButton:(UIButton*)button
{
button.layer.cornerRadius = 10;
button.clipsToBounds = YES;
button.layer.borderColor=[[UIColor lightGrayColor] CGColor];
button.layer.borderWidth=1.0;
[button.titleLabel setTextAlignment:NSTextAlignmentCenter];
[button.titleLabel setFont:[UIFont fontWithName:#"HelveticaNeue-UltraLight" size:20]];
[button setTitle:#"0" forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
return button;
}
-(UITextField*)formatTextField:(UITextField*)textField
{
[textField setFont:[UIFont fontWithName:#"HelveticaNeue-UltraLight" size:20]];
textField.backgroundColor=[UIColor whiteColor];
textField.layer.borderColor=[[UIColor lightGrayColor] CGColor];
textField.layer.cornerRadius = 10;
textField.layer.borderWidth=1.0;
[textField setTextAlignment:NSTextAlignmentCenter];
textField.clipsToBounds=YES;
textField.text=#"";
textField.enabled=NO;
return textField;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"ItemCellID" forIndexPath:indexPath];
// Configure the cell...
OrderedProduct *orderedProduct=self.orderedProductsArray[indexPath.row];
//NSLog (#"ordered Product %#",orderedProduct.productID);
UITextField *qualityField=[[UITextField alloc] initWithFrame:CGRectMake(113,23,324,30)];
qualityField=[self formatTextField:qualityField];
[cell addSubview:qualityField];
UITextField *sizeField=[[UITextField alloc] initWithFrame:CGRectMake(445, 24, 142, 30)];
sizeField=[self formatTextField:sizeField];
[cell addSubview:sizeField];
UITextField *totalPriceField=[[UITextField alloc] initWithFrame:CGRectMake(786,24,137,30)];
totalPriceField=[self formatTextField:totalPriceField];
[cell addSubview:totalPriceField];
UIButton *quantityButton=[[UIButton alloc] initWithFrame:CGRectMake(595,24,60,30)];
quantityButton=[self formatButton:quantityButton];
[cell addSubview:quantityButton];
UIButton *priceButton=[[UIButton alloc] initWithFrame:CGRectMake(663,24,119,30)];
priceButton=[self formatButton:priceButton];
[cell addSubview:priceButton];
UIImageView *imageView=[[UIImageView alloc] initWithFrame:CGRectMake(5,15,100,50)];
[cell addSubview:imageView];
UIButton *removeButton=(UIButton*)[cell viewWithTag:kRemoveButton];
if (self.selectedOrder.status==[NSNumber numberWithInt:kOrderStatusProvisional])
{
quantityButton.enabled=YES;
quantityButton.backgroundColor=[Settings getInstance].enabledButtonColor;
[quantityButton addTarget:self action:#selector(quantityButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
priceButton.enabled=YES;
priceButton.backgroundColor=[Settings getInstance].enabledButtonColor;
removeButton.hidden=NO;
[removeButton addTarget:self action:#selector(removeButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
}
else
{
quantityButton.enabled=NO;
quantityButton.backgroundColor=[Settings getInstance].disabledButtonColor;
priceButton.enabled=NO;
priceButton.backgroundColor=[Settings getInstance].disabledButtonColor;
removeButton.hidden=YES;
}
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setCurrencyCode:#"GBP"];
[numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];
imageView.image=[self.imageCache objectForKey:orderedProduct.product.productImageName];
UITapGestureRecognizer *tgr=[[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(imageViewTapped:)];
imageView.userInteractionEnabled=YES;
[imageView addGestureRecognizer:tgr];
qualityField.text=orderedProduct.product.name;
sizeField.text=orderedProduct.product.productSize.productSize;
quantityButton.titleLabel.text=[NSString stringWithFormat:#"%#",orderedProduct.quantity];
[quantityButton setTitle:[NSString stringWithFormat:#"%#",orderedProduct.quantity] forState:UIControlStateNormal];
float price=[orderedProduct.price integerValue]/100; // server price is in pennies
float totalPrice=price*[orderedProduct.quantity integerValue];
[priceButton setTitle:[numberFormatter stringFromNumber:[NSNumber numberWithFloat:price]] forState:UIControlStateNormal];
totalPriceField.text=[numberFormatter stringFromNumber:[NSNumber numberWithFloat:totalPrice]];
return cell;
}
Not able to post images yet so below is a crude description of what Instruments is saying,
Snapshot Growth
Generation B 3.64MB
VM: UILabel (CALayer) 964KB
VM: UITextFieldLabel (CALayer) 792KB
VM: CoreAnimation 788KB

Remove a subview from UIViewController

I'm adding a subview to the main view but then I cant remove it from this view.
NextViewController *nextView = [[NextViewController alloc] init];
nextView.transitioningDelegate = self;
nextView.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self.presentedViewController.view addSubview:nextView.view];
nextView.view.frame = CGRectMake(724, 80, 300, 150);
UIButton *stayButton = [[UIButton alloc] initWithFrame:CGRectMake(101, 94, 90, 49)];
[stayButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[stayButton setTitle:#"Detener" forState:UIControlStateNormal];
[stayButton addTarget:self
action:#selector(waitForNextView)
forControlEvents:UIControlEventTouchUpInside];
[nextView.view addSubview:stayButton];
stayButton.titleLabel.font = [UIFont systemFontOfSize:25];
[stayButton setTitleColor:[UIColor colorWithRed:(255/255.0) green:(255/255.0) blue:(255/255.0) alpha:1] forState:UIControlStateNormal];
here I'm adding a button to the view and then when the button is pushed it goes`-
(void)waitForNextView{
transition = NO;
NextViewController *nextView = [[NextViewController alloc] init];
SectionViewController *sectionView = [[SectionViewController alloc]init];
[self.locationManager stopRangingBeaconsInRegion:self.beaconRegion];
actualSection = 0;
[NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:#selector(dismissView2) userInfo:nil repeats:NO];
}
I've tried with:
[nextView.view removeFromSuperView];
[nextView.presentedViewController removeFromParentViewController];
But I don't know what else can I do :S
If you want more information, nextView is a UIViewController of 300x100 size. I want to present it and then remove it when I hit the button, that's all.
I would be great if someone can help me.
Thanks
You are creating different reference and then you're trying to remove it from its superview while not being added at all. I will try to explain:
1. When you're adding nextView.view to self.view you have created a instance like this
NextViewController *nextView = [[NextViewController alloc] init];
2. When you're trying to remove it, instead of referring to the instance above you're creating a brand new one again in your waitForNextView method like so again
NextViewController *nextView = [[NextViewController alloc] init];
and then you're trying to remove it. Please note that the last instance of nextView has not being added anywhere yet, and this is the reason your code doesn't work.
In order to work you should refer to the first reference you've added to self.view. Please adjust your code as shown below
In your ViewController.m
#interface ViewController()
{
NextViewController *nextView;
}
When adding your viewController
nextView = [[NextViewController alloc] init];
nextView.transitioningDelegate = self;
nextView.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
[self.presentedViewController.view addSubview:nextView.view];
nextView.view.frame = CGRectMake(724, 80, 300, 150);
UIButton *stayButton = [[UIButton alloc] initWithFrame:CGRectMake(101, 94, 90, 49)];
[stayButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[stayButton setTitle:#"Detener" forState:UIControlStateNormal];
[stayButton addTarget:self
action:#selector(waitForNextView)
forControlEvents:UIControlEventTouchUpInside];
[nextView.view addSubview:stayButton];
stayButton.titleLabel.font = [UIFont systemFontOfSize:25];
[stayButton setTitleColor:[UIColor colorWithRed:(255/255.0) green:(255/255.0) blue:(255/255.0) alpha:1] forState:UIControlStateNormal];
And finally in your IBAction method
-(void)waitForNextView{
transition = NO;
[self.locationManager stopRangingBeaconsInRegion:self.beaconRegion];
actualSection = 0;
[nextView removeFromSuperview];
}
The problem here is that you are adding the button as a subview to the view of nextView, so removing the view of nextView won't work.
If you add a tag to your button, then you can retrieve the subview by using the tag. Eg. When you define your button:
[stayButton setTag:1];
Then in the waitForNextView method, you can get the control like this:
UIButton *stayButton = (UIButton*)[nextView.view viewWithTag:1];
[stayButton removeFromSuperView];
use this code in the methode dismissView2
for (UIView *subview in view.subviews ){
[subview removeFromSuperview];
}

ChildViewController not able to modify its UI after creation

I have a view controller which is being added as a child view controller. The problem is that after the child controller creates its view, I am not able to modify it.
It loads everything properly, but when I want to hide a text field on clicking a button (textfield.hidden = YES), nothing happens!
This is my loadView :
-(void)loadView {
self.waitingPopup = [[WaitingPopupViewController alloc]initWithLabel:#"loading salon"];
self.view=[[UIView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame];
// self.view.frame=CGRectMake(0, -20, self.view.frame.size.width, self.view.frame.size.height);
scrollableTable=[[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
scrollableTable.delegate=self;
scrollableTable.dataSource=self;
[self.view addSubview:scrollableTable];
headerHolder=[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-44)];
//creating and adding backgroundImage view container and setting the image
// saloonHomeImage.backgroundColor = [UIColor grayColor];
saloonHomeImage.frame=CGRectMake(self.view.frame.origin.x, 0, self.view.frame.size.width, self.view.frame.size.height);
saloonHomeImage.contentMode = UIViewContentModeScaleAspectFill;
//[saloonHomeImage setBackgroundColor:[UIColor redColor]];
[headerHolder setBackgroundColor:[UIColor grayColor]];
[headerHolder addSubview:saloonHomeImage];
//creating and adding saloonheader label
saloonLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 32, self.view.frame.size.width, 48)];
saloonLabel.text=#"";
saloonLabel.textAlignment=NSTextAlignmentCenter;
[saloonLabel setTextColor:[UIColor whiteColor]];
[saloonLabel setFont:[UIFont fontWithName:#"vevey" size:48]];
[headerHolder addSubview:saloonLabel];
//creating and adding book appointment button
UIButton *bookAppointmentButton=[UIButton buttonWithType:UIButtonTypeSystem];
NSLog(#"%f", self.view.frame.size.height-97.5);
bookAppointmentButton.frame=CGRectMake(self.view.frame.origin.x, self.view.frame.size.height-97.5, 216, 53);
[bookAppointmentButton setBackgroundImage:[UIImage imageNamed:#"bg-left.png"] forState:UIControlStateNormal];
[bookAppointmentButton setTitle:#"BOOK APPOINTMENT" forState:UIControlStateNormal];
[bookAppointmentButton addTarget:self action:#selector(bookAppointmentAction) forControlEvents:UIControlEventTouchUpInside];
[bookAppointmentButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
[headerHolder addSubview:bookAppointmentButton];
UIButton *callButton=[UIButton buttonWithType:UIButtonTypeSystem];
callButton.frame=CGRectMake(216, self.view.frame.size.height-97.5, self.view.frame.size.width-216, 53);
[callButton setBackgroundImage:[UIImage imageNamed:#"bg-right.png"] forState:UIControlStateNormal];
[callButton addTarget:self action:#selector(callButtonAction) forControlEvents:UIControlEventTouchUpInside];
[callButton setTitle:#"CALL" forState:UIControlStateNormal];
[callButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
[headerHolder addSubview:callButton];
[self getSalonDetails];
loading=[[UIImageView alloc] init];
loading.frame=CGRectMake(130,200,40,36);
[loading setBackgroundColor:[UIColor clearColor]];
loading.animationImages = [NSArray arrayWithObjects:
[UIImage imageNamed:#"spinner-1.png"],
[UIImage imageNamed:#"spinner-2.png"],
[UIImage imageNamed:#"spinner-3.png"],
[UIImage imageNamed:#"spinner-4.png"],
[UIImage imageNamed:#"spinner-5.png"],
[UIImage imageNamed:#"spinner-6.png"],
[UIImage imageNamed:#"spinner-7.png"],
[UIImage imageNamed:#"spinner-8.png"],[UIImage imageNamed:#"spinner-9.png"],nil];
loading.animationDuration = 1.0f;
loading.animationRepeatCount = 0;
[loading startAnimating];
[self.view addSubview:loading];
loadingText = [[UILabel alloc]initWithFrame:CGRectMake(90, 240, 200, 40)];
loadingText.text = #"loading salon";
[loadingText setFont:GOTHIC_FONT(22)];
[loadingText setTextColor:[UIColor whiteColor]];
[self.view addSubview:loadingText];
articles=[Model getArticles];
}
- (void) getSalonDetails{
[[MyDataModel sharedDataModel] getSalonDetails];
}
This is the delegate method which is trying to set some fields hidden. This delegate is called when an NSURLSession call completes successfully. The control comes here as per logs but nothing gets hidden. When I add a breakpoint and inspect the fields, every object is shown as nil. If this class is used as the main view controller, I've found everything works. On making it a child view, nothing works.
-(void)salonDetailsRecievedDelegate:(BOOL)success andStatusCode:(int)statusCode{
[loading stopAnimating];
self.loading.hidden = YES;
self.loadingText.hidden = YES;
saloonLabel.text = #"this is texT";
if(success){
//
}
}
What I think here is that salonDetailsRecievedDelegate isn't called from the main thread, try any of the following:
1) call it in the main thread from your model as follows:
dispatch_async(dispatch_get_main_queue(), ^{
[self.delegate salonDetailsRecievedDelegate:success andStatusCode:status];
});
2) change its implementation as follows:
-(void)salonDetailsRecievedDelegate:(BOOL)success andStatusCode:(int)statusCode{
dispatch_async(dispatch_get_main_queue(), ^{
[loading stopAnimating];
self.loading.hidden = YES;
self.loadingText.hidden = YES;
saloonLabel.text = #"this is texT";
if(success){
//
}
});
}

Resources