dynamically generated UIButton in iOS 5 ARC causes deallocated instance crash - ios

I have a a class I created to generate UIButton's I add to my UIView. This worked great until my conversion to ARC yesterday, not I get the following error:
-[OrderTypeButton performSelector:withObject:withObject:]: message sent to deallocated instance 0x12449f70
Here is the code to add the button to my UIView (actually a subview in my main UIView):
OrderTypeButton *btn = [[OrderTypeButton alloc]initWithOrderType:#"All Orders" withOrderCount:[NSString stringWithFormat:#"%i",[self.ordersPlacedList count]] hasOpenOrder:NO];
btn.view.tag = 6969;
btn.delegate = self;
[btn.view setFrame:CGRectMake((col * width)+ colspacer, rowHeight + (row * height), frameWidth, frameHeight)];
[self.statsView addSubview:btn.view];
And here is my class header:
#import <UIKit/UIKit.h>
#protocol OrderTypeButtonDelegate
-(void) tapped:(id)sender withOrderType:(NSString*) orderType;
#end
#interface OrderTypeButton : UIViewController {
id<OrderTypeButtonDelegate> __unsafe_unretained delegate;
IBOutlet UILabel *lblOrderType;
IBOutlet UILabel *lblOrderCount;
NSString *orderType;
NSString *orderCount;
BOOL hasOpenOrder;
}
#property (nonatomic, strong) IBOutlet UIButton *orderButton;
#property (nonatomic, strong) IBOutlet UILabel *lblOrderType;
#property (nonatomic, strong) IBOutlet UILabel *lblOrderCount;
#property (nonatomic, strong) NSString *orderType;
#property (nonatomic, strong) NSString *orderCount;
#property (nonatomic, assign) BOOL hasOpenOrder;
#property (nonatomic, unsafe_unretained) id<OrderTypeButtonDelegate> delegate;
-(id) initWithOrderType: (NSString *) anOrderType withOrderCount: (NSString *) anOrderCount hasOpenOrder: (BOOL) openOrder;
-(IBAction)btnTapped:(id)sender;
#end
Implementation:
#import "OrderTypeButton.h"
#implementation OrderTypeButton
#synthesize orderButton;
#synthesize lblOrderType, lblOrderCount, orderType, orderCount, hasOpenOrder, delegate;
-(id) initWithOrderType: (NSString *) anOrderType withOrderCount: (NSString *) anOrderCount hasOpenOrder: (BOOL) openOrder {
if ((self = [super init])) {
self.orderType = anOrderType;
self.orderCount = anOrderCount;
self.hasOpenOrder = openOrder;
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
self.lblOrderType.text =[NSString stringWithFormat:#"%#", self.orderType];
self.lblOrderCount.text = [NSString stringWithFormat:#"%#", self.orderCount];
if (self.hasOpenOrder) {
[self.orderButton setBackgroundImage:[UIImage imageNamed:#"background-order-btn-red.png"] forState:UIControlStateNormal];
self.lblOrderType.textColor = [UIColor whiteColor];
self.lblOrderCount.textColor = [UIColor whiteColor];
}
}
-(IBAction)btnTapped:(id)sender {
NSLog(#"TAPPED");
if ([self delegate] ) {
[delegate tapped:sender withOrderType:self.orderType];
}
}
- (void)viewDidUnload
{
[self setOrderButton:nil];
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
#end
This seems fairly simple what I am doing here, not sure what changed with ARC that is causing me problems.

Maybe ARC autorelease created button, try to store created buttons in Array
//.h file
#property (nonatomic, strong) NSArray *buttonsArray
//.m file
#synthesize buttonsArray
...
- (void)viewDidLoad {
buttonsArray = [NSArray array];
...
OrderTypeButton *btn = [[OrderTypeButton alloc]initWithOrderType:#"All Orders"
withOrderCount:[NSString stringWithFormat:#"%i",[self.ordersPlacedList count]]
hasOpenOrder:NO];
btn.view.tag = 6969;
btn.delegate = self;
[btn.view setFrame:CGRectMake((col * width)+ colspacer, rowHeight + (row * height), frameWidth, frameHeight)];
[self.statsView addSubview:btn.view];
//Add button to array
[buttonsArray addObject:btn];
Also this approach will help if you want to change buttons, or remove some specific button from view

Related

Xcode use of undeclared identifier

I am new to coding and had some basic knowledge but i am building out my first app from a tutorial and have a issue i can't figure out and after a few days of looking figured i would just ask. I get an error in my implementation file when initializing the object in the view did load.
It says use of undeclared identifier. any help would be greatly appreciated.
Here is my view controller.m
#import "ViewController.h"
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSLog(#"titleLabel.text = %#", self.titleLabel.text);
self.bandObject = [[BandObject alloc] init];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
return YES;
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
self.bandObject.name = self.nameTextField.text;
[self.nameTextField resignFirstResponder];
return YES;
}
-(BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
self.bandObject.name =self.nameTextField.text;
[self saveBandObject];
[self.nameTextField resignFirstResponder];
return YES;
}
-(BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
self.saveNotesButton.enabled = YES;
return YES;
}
-(BOOL)textViewShouldEndEditing:(UITextView *)textView
{
self.bandObject.notes = self.notesTextView.text;
[self.notesTextView resignFirstResponder];
self.saveNotesButton.enabled = NO;
return YES;
}
- (IBAction)saveNotesButtonTouched:(id)sender
{
[self textViewShouldEndEditing:self.notesTextView];
}
- (IBAction)ratingStepperValueChanged:(id)sender
{
self.ratingValueLabel.text = [NSString stringWithFormat:#"%g",self.ratingStepper.value];
self.bandObject.rating = (int)self.ratingStepper.value;
}
- (IBAction)tourStatusSegmentedControlValueChanged:(id)sender
{
self.bandObject.touringStatus = self.touringStatusSegmentedControl.selectedSegmentIndex;
}
- (IBAction)haveSeenLiveSwitchValueChanged:(id)sender
{
self.bandObject.haveSeenLive = self.haveSeenLiveSwitch.on;
}
#end
and here is my .h
#import <UIKit/UIKit.h>
#import "WBABand.h"
#interface ViewController : UIViewController <UITextFieldDelegate, UITextViewDelegate>
#property (nonatomic, strong) WBABand *bandObject;
#property (nonatomic, weak) IBOutlet UILabel *titleLabel;
#property (nonatomic, weak) IBOutlet UITextField *nameTextField;
#property (nonatomic, weak) IBOutlet UITextView *notesTextView;
#property (nonatomic, weak) IBOutlet UIButton *saveNotesButton;
#property (nonatomic, weak) IBOutlet UIStepper *ratingStepper;
#property (nonatomic, weak) IBOutlet UILabel *ratingValueLabel;
#property (nonatomic, weak) IBOutlet UISegmentedControl *touringStatusSegmentedControl;
#property (nonatomic, weak) IBOutlet UISwitch *haveSeenLiveSwitch;
- (IBAction)saveNotesButtonTouched:(id)sender;
- (IBAction)ratingStepperValueChanged:(id)sender;
- (IBAction)tourStatusSegmentedControlValueChanged:(id)sender;
- (IBAction)haveSeenLiveSwitchValueChanged:(id)sender;
#end
It is because you have an object in your .h called WBABand. And in your .m your are initializing a BandObject which does not exists.
Change this [[BandObject alloc] init];
to this [[WBABand alloc] init];
When you run into an issue, please try to narrow it down to the shortest code block possible to reproduce. At the very least, you should be pointing out the line that shows the error so that contributors can help you easier.
You are trying to instantiate an instance of BandObject, but the class you should be trying to instantiate is WBABand.
self.bandObject = [[WBABand alloc] init];

Object being populated shows null fields in log (IOS, OBJ-C)

I'm populating an object's fields from Labels, when displaying in Log the label is the correct value, but the object's field is null. I'm coming over from an Android/ Java background and this is just awkward.
Any help would be great.
To be clear, the "soil type field" log shows "example"while the "soil type" log shows (null)
- (IBAction)saveButton:(id)sender {
Soil *thisSoil = self.thisSoil;
thisSoil.soilType = self.soilNameField.text;
NSLog(#"soil type field %#", self.soilNameField.text);
NSLog(#"soil type: %#", thisSoil.soilType);
thisSoil.frictionAngle = [self.frictionAngleValue.text integerValue];
if ([self.soilUnitsSwitch isOn] ) {
thisSoil.cohesion = [self.cohesionValue.text doubleValue];
thisSoil.unitWeight = [self.unitWeightValue.text doubleValue];
}else{
thisSoil.cohesion = [self.cohesionValue.text doubleValue];
thisSoil.unitWeight = [self.unitWeightValue.text doubleValue];
}
[self.delegate SoilCreatorViewController:self didFinishItem:thisSoil];
[self.navigationController popViewControllerAnimated:YES];
}
The entire controller .m file
#import "SoilCreatorViewController.h"
#define IMPERIAL_TO_METRIC 0.3048
#define KG_TO_LBS 2.2
#interface SoilCreatorViewController ()
#end
#implementation SoilCreatorViewController
- (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 from its nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)soilQuestions:(id)sender {
[self popupmaker :#"Friction Angle" : #"Phi is the angle of internal friction for soil, which governs soil strength and resistance. This value should be attained from competent field testing and the judgment of a licensed engineer."];
[self popupmaker :#"Soil Cohesion": #"Cohesion defines the non-stress dependent shear strength of soil and should be used with caution. Typically,cohesion occurs in stiff, over-consolidated clays or cemented native soils. Cohesion should be neglected if the designer is unsure of its presence."];
}
- (IBAction)SwitchDidChange:(id)sender {
if ([sender isOn]) {
self.cohesionUnits.text = #"Ft";
self.unitWeightUnits.text= #"M";
}else{
self.cohesionUnits.text = #"M";
self.unitWeightUnits.text = #"M";
}
}
- (IBAction)unitWtDidChange:(id)sender {
self.unitWeightValue.text = [NSString stringWithFormat:#"%.1f", (double)self.unitWeightStepper.value];
}
- (IBAction)frictionAngleDidChange:(id)sender {
self.frictionAngleValue.text = [NSString stringWithFormat:#"%d", (int)self.frictionAngleStepper.value];
}
- (IBAction)cohesionDidChange:(id)sender {
self.cohesionValue.text = [NSString stringWithFormat:#"%.1f", (double)self.cohesionStepper.value];
}
- (IBAction)textFieldDismiss:(id)sender {
[[self view] endEditing:YES];
}
- (IBAction)UnitSwitch:(id)sender {
if ([sender isOn]) {
self.unitWeightUnits.text = #"LBS/cubic Ft.";
self.cohesionUnits.text = #"imp";
}else{
self.unitWeightUnits.text = #"KG/m3";
self.cohesionUnits.text = #"met";
}
}
- (IBAction)cancelButton:(id)sender {
[self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)saveButton:(id)sender {
Soil *thisSoil = self.thisSoil;
thisSoil.soilType = self.soilNameField.text;
NSLog(#"soil type field %#", self.soilNameField.text);
NSLog(#"soil type: %#", thisSoil.soilType);
thisSoil.frictionAngle = [self.frictionAngleValue.text integerValue];
if ([self.soilUnitsSwitch isOn] ) {
thisSoil.cohesion = [self.cohesionValue.text doubleValue];
thisSoil.unitWeight = [self.unitWeightValue.text doubleValue];
}else{
thisSoil.cohesion = [self.cohesionValue.text doubleValue];
thisSoil.unitWeight = [self.unitWeightValue.text doubleValue];
}
[self.delegate SoilCreatorViewController:self didFinishItem:thisSoil];
[self.navigationController popViewControllerAnimated:YES];
}
-(void)popupmaker:(NSString *)title :(NSString *)message{
UIAlertView * alert =[[UIAlertView alloc ] initWithTitle:title
message:message
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil
];
[alert show];
}
#end
The .h file
#import "Soil.h"
#class SoilCreatorViewController;
#protocol SoilCreatorViewDelegate <NSObject>
-(void)SoilCreatorViewController:(SoilCreatorViewController *)controller didFinishItem:(Soil *)item;
#property (nonatomic, weak) id <SoilCreatorViewDelegate> delegate;
#end
#import <UIKit/UIKit.h>
#import "CalculationDetailViewController.h"
#interface SoilCreatorViewController : UIViewController
#property (nonatomic,weak) id<SoilCreatorViewDelegate> delegate;
#property (weak, nonatomic) IBOutlet UITextField *soilNameField;
#property (weak, nonatomic) IBOutlet UISwitch *soilUnitsSwitch;
#property (nonatomic,strong) Soil *thisSoil;
#property (weak, nonatomic) IBOutlet UIStepper *frictionAngleStepper;
#property (weak, nonatomic) IBOutlet UIStepper *unitWeightStepper;
#property (weak, nonatomic) IBOutlet UIStepper *cohesionStepper;
#property (weak, nonatomic) IBOutlet UILabel *unitWeightValue;
#property (weak, nonatomic) IBOutlet UILabel *frictionAngleValue;
#property (weak, nonatomic) IBOutlet UILabel *cohesionValue;
#property (weak, nonatomic) IBOutlet UILabel *unitWeightUnits;
#property (weak, nonatomic) IBOutlet UILabel *cohesionUnits;
- (IBAction)soilQuestions:(id)sender;
- (IBAction)SwitchDidChange:(id)sender;
- (IBAction)unitWtDidChange:(id)sender;
- (IBAction)frictionAngleDidChange:(id)sender;
- (IBAction)cohesionDidChange:(id)sender;
- (IBAction)textFieldDismiss:(id)sender;
- (IBAction)cancelButton:(id)sender;
- (IBAction)saveButton:(id)sender;
-(void)popupmaker:(NSString *)title :(NSString *)message;
#end
I don't see any code that sets up thisSoil. At some point in your code, you need to write something like
self.thisSoil = [[Soil alloc] init];
or self.thisSoil will stay nil forever.

UIView not updating in iPhone App

I am new to iPhone App development, below is ViewController.m
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self updateMyView];
}
- (IBAction)clickButtonResult:(id)sender
{
enteredText = [textField text]; // Or textField.text
NSLog(#"Number 1 : %i", number_1);
NSLog(#"Number 2 : %i", number_2);
NSLog(#"Entered Text is %#", enteredText);
int NUM_RESULT = number_1 + number_2;
verify_result = [NSString stringWithFormat:#"%i", NUM_RESULT];
NSLog(#"Verify Result : %#", verify_result);
NSString *final_result = [NSString stringWithFormat:#"%d", [enteredText isEqualToString:verify_result]];
int final_int_result = [final_result integerValue];
if (final_int_result) {
//result_label.text = #"Correct";
NSLog(#"Correct");
[self updateMyView];
} else {
//result_label.text = #"Wrong";
NSLog(#"Wrong");
}
}
- (int)getRandomNumberBetween:(int)min maxNumber:(int)max
{
return min + arc4random() % (max - min + 1);
}
- (void) updateMyView
{
number_1 = [self getRandomNumberBetween:10 maxNumber:99];
number_2 = [self getRandomNumberBetween:10 maxNumber:99];
num_1.text = [NSString stringWithFormat:#"%i", number_1];
num_2.text = [NSString stringWithFormat:#"%i", number_2];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
and ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
{
IBOutlet UILabel *num_1;
IBOutlet UILabel *num_2;
IBOutlet UILabel *result_label;
IBOutlet UITextField *textField;
int number_1;
int number_2;
NSString *verify_result;
NSString *enteredText;
BOOL display_result;
}
- (IBAction)clickButtonResult:(id)sender;
#end
After entering the correct result the UIView should be updated with updateMyView function but it is not happening.
Can anyone help here??
First of all, start using Properties.
ViewController.h
#interface ViewController : UIViewController
#property (nonatomic, weak) IBOutlet UILabel *num_1;
#property (nonatomic, weak) IBOutlet UILabel *num_2;
#property (nonatomic, weak) IBOutlet UILabel *resultLabel;
#property (nonatomic, weak) IBOutlet UITextField *textField;
#property (nonatomic) NSInteger number_1;
#property (nonatomic) NSInteger number_2;
#property (nonatomic, strong) NSString *verifyResult;
#property (nonatomic, strong) NSString *enteredText;
#property (nonatomic) BOOL displayResult;
- (IBAction)clickButtonResult:(id)sender;
#end
In ViewController.m code use self.{name of property}, for example self.textField for the textField property.
Now, go to Interface builder and connect the IBOutlet properties to the right objects. (click with right button on File's Owner)
Try changing num_1.text in viewDidLoad to make sure you have access to that label from your UIViewController.
So in viewDidLoad, just put something like
num1.text = #"Updated from viewDidLoad"
Make sure that you have connected num_1 and num_2 with the UILabels properly. It seems that you have not connected these.
Just move [self updateMyView]; outside the if statements in clickButtonResult: function
then it will update the view when click the button.
if (final_int_result) {
//result_label.text = #"Correct";
NSLog(#"Correct");
} else {
//result_label.text = #"Wrong";
NSLog(#"Wrong");
}
[self updateMyView];

Pass info to multiple viewControllers via iCarousel

I'm trying to implement an iCarousel that will pass information on to two other view controllers when an image is chosen. While the iCarousel loads perfectly and transitions to the next VC, the information is not displayed on the new VC.
The approach I chose was to create an NSObject file. I can't simply pass the info from VC to VC since I have several VC's that need the information and I'd prefer not to create a singleton or use AppDelegate if possible.
FYI: I do have a tap gesture recognizer added on top of the UIView that acts as the segue to the next VC if that makes any difference.
I've tried every possible tutorial out there and can't seem to figure out my problem. I just need to display a text label and a picture, which should really be pretty easy. Can someone take a quick glance at my code to see what I'm doing wrong?
My NSObject File:
#import <Foundation/Foundation.h>
#interface Stop : NSObject
#property (nonatomic, strong) NSString *title;
#property (nonatomic, strong) NSString *image;
#end
First ViewController.h (with iCarousel on it):
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
#import "iCarousel.h"
#import "DirectionsViewController.h"
#import "Stop.h"
#interface StopsMenuViewController : UIViewController <iCarouselDataSource, iCarouselDelegate>
#property (strong, nonatomic) IBOutlet iCarousel *carousel;
#property (strong, nonatomic) IBOutlet UILabel *titleLabel;
//Title
#property (nonatomic, strong) NSArray *stopTitles;
#property (nonatomic, strong) NSString *stopChosen;
//Image
#property (nonatomic, strong) NSArray *stopImages;
#property (nonatomic, strong) NSString *imageChosen;
#end
First ViewController.m:
#import "StopsMenuViewController.h"
#interface StopsMenuViewController () {
NSMutableArray *allInfo; }
#end
#implementation StopsMenuViewController
#synthesize titleLabel, carousel, stopImages, stopTitles, stopChosen, imageChosen;
- (void)awakeFromNib {
NSString *myPlist = [[NSBundle mainBundle] pathForResource:#"Chinatown" ofType:#"plist"];
NSDictionary *rootDictionary = [[NSDictionary alloc] initWithContentsOfFile:myPlist];
self.stopImages = [rootDictionary objectForKey:#"StopImages"];
self.stopTitles = [rootDictionary objectForKey:#"StopTitles"];
}
- (void)carouselDidScroll:(iCarousel *)carousel {
[titleLabel setText:[NSString stringWithFormat:#"%#", [self.stopTitles
objectAtIndex:self.carousel.currentItemIndex]]];
}
- (void)dealloc {
self.carousel.delegate = nil;
self.carousel.dataSource = nil;
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:#"toDirections"])
{
DirectionsViewController *dvc = [segue destinationViewController];
int itemId = [self.carousel currentItemIndex];
NSIndexPath *path = [NSIndexPath indexPathForRow:itemId inSection:0];
Stop *current = [allInfo objectAtIndex:path.row];
[dvc setPassInfo:current];
}
}
- (void)viewDidLoad {
[super viewDidLoad];
self.carousel.type = iCarouselTypeCoverFlow2;
allInfo = [[NSMutableArray alloc] init];
Stop *info = [[Stop alloc] init];
stopChosen = [NSString stringWithFormat:#"%#", [self.stopTitles objectAtIndex:self.carousel.currentItemIndex]];
[info setTitle:stopChosen];
[allInfo addObject:info];
info = [[Stop alloc] init];
self.imageChosen = [NSString stringWithFormat:#"%#", [self.stopImages
objectAtIndex:self.carousel.currentItemIndex]];
[info setTitle:self.imageChosen];
[allInfo addObject:info];
}
- (void)viewDidUnload
{
[super viewDidUnload];
self.carousel = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return YES;
}
- (NSUInteger)numberOfItemsInCarousel:(iCarousel *)carousel {
return [self.stopImages count];
}
- (NSUInteger)numberOfVisibleItemsInCarousel:(iCarousel *)carousel {
return 4;
}
- (UIView *)carousel:(iCarousel *)_carousel viewForItemAtIndex:(NSUInteger)index reusingView:(UIView *)view {
if (view == nil)
{
view = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[self.stopImages objectAtIndex:index]]];
}
return view;
}
- (void)carousel:(iCarousel *)carousel didSelectItemAtIndex:(NSInteger)index {
DirectionsViewController *dvc = [self.storyboard instantiateViewControllerWithIdentifier:#"dvc"];
[self.navigationController pushViewController:dvc animated:YES];
}
#end
Second ViewController.h:
#import <UIKit/UIKit.h>
#import "Stop.h"
#interface DirectionsViewController : UIViewController
#property (strong, nonatomic) IBOutlet UILabel *titleLabel;
#property (strong, nonatomic) IBOutlet UIImageView *imageBox;
#property (nonatomic, strong) Stop *PassInfo;
#property (nonatomic, strong) NSString *stopTitle;
#property (nonatomic, strong) NSString *myStopTitle;
#end
Second ViewController.m:
#import "DirectionsViewController.h"
#interface DirectionsViewController ()
#end
#implementation DirectionsViewController
#synthesize PassInfo;
- (void)viewDidLoad {
[super viewDidLoad];
[self.titleLabel setText:[PassInfo title]];
UIImage *image = [UIImage imageNamed:[PassInfo image]];
[self.imageBox setImage:image];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
#end
Instead of
- (void)carousel:(iCarousel *)carousel didSelectItemAtIndex:(NSInteger)index {
DirectionsViewController *dvc = [self.storyboard instantiateViewControllerWithIdentifier:#"dvc"];
[self.navigationController pushViewController:dvc animated:YES];
}
Use
- (void)carousel:(iCarousel *)carousel didSelectItemAtIndex:(NSInteger)index {
[self performSegueWithIdentifier:#"toDirections" sender:self];
}
In your code, you're instantiating the second view controller and presenting it, which is not the same as performing a segue. Therefore the method - prepareForSegue:sender: will not be invoked.

instance variable returning null in viewDidAppear but fine in viewDidLoad

For some reason my instance variable (in my viewcontroller) is returning null in viewDidAppear but its returning the correct value in viewDidLoad..
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(#"viewDidLoad: %#",self.product.sku);
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
NSLog(#"viewDidAppear: %#",self.product.sku);
[self adjustViews];
}
This only happens when i'm loading my viewController from my appdelegate like below:
ProductDetailViewController *controller = [[ProductDetailViewController alloc] initWithProduct:product];
[(UINavigationController *)self.tabBarController.selectedViewController pushViewController:controller animated:YES];
If i access my controller through other screen it works fine...
DProduct *product = [self.resultsController objectAtIndexPath:indexPath];
ProductDetailViewController *detailViewController = [[ProductDetailViewController alloc] initWithProduct:product];
[self.navigationController pushViewController:detailViewController animated:YES];
initWithProduct function
- (id)initWithProduct:(DProduct *)product {
self = [super init];
if (self) {
self.product = product;
self.title = product.sku;
}
NSLog(#"initwithproduct: %#",self.product.sku);
return self;
}
setProduct function
- (void)setProduct:(DProduct *)product {
NSLog(#"SET PRODUCT WAS CALLED...%#",product.sku);
product_ = product;
if (product) {
[self.cartButton removeFromSuperview];
BOOL outOfStock = [product.stock unsignedIntegerValue] == 0;
NSString *title = outOfStock ? NSLocalizedString(#"Out of Stock", nil) : NSLocalizedString(#"Add To Cart", nil);
ThemedButton *cartButton = [ThemedButton buttonWithTitle:title style:outOfStock ? ThemedButtonStyleRed : ThemedButtonStylePink];
[cartButton addTarget:nil action:#selector(addToCart:) forControlEvents:UIControlEventTouchUpInside];
[cartButton sizeToFit];
cartButton.enabled = !outOfStock;
[self addSubview:cartButton];
self.cartButton = cartButton;
[self setupInterface];
}
}
Declarations for product and sku
#interface ProductDetailViewController()
#property (nonatomic, strong) ProductDetailView *detailView;
#property (nonatomic, strong) UIScrollView *scrollView;
#property (nonatomic, strong) DProduct *product;
#property (nonatomic, assign) BOOL keyboardIsShown;
- (void)configureDetailView;
- (void)adjustViews;
- (NSURL *)productURL;
#end
#implementation ProductDetailViewController
#synthesize detailView = detailView_;
#synthesize scrollView = scrollView_;
#synthesize keyboardIsShown = keyboardIsShown_;
#synthesize product = product_;
#interface DProduct : DAsset
#property (nonatomic, retain) NSNumber * available;
#property (nonatomic, retain) NSString * detail;
#property (nonatomic, retain) NSNumber * price;
#property (nonatomic, retain) NSNumber * shipping;
#property (nonatomic, retain) NSString * sku;
The way to find such things is to switch from an ivar to a property, write your own setter, then add a nslog if the new value is nil. Put a breakpoint on the log message and you will discover how it's getting nilled.

Resources