Why won't this code allocate a subView?

Go To StackoverFlow.com


This is my code where I'm trying to create a subView... I'm using XCode4 with StoryBoards. The app is crashing on the 2nd line where it is allocating subView with EXC_BAD_ACCESS. vFrame has valid content. What is wrong with this? (I'm using XCode4 with Storyboards, btw).

- (void)viewDidLoad
    [super viewDidLoad];

    CGRect vFrame = CGRectMake(60,100,200,200);
    subView = [[UIView alloc] initWithFrame:vFrame];
    subView.backgroundColor = [UIColor redColor];
    [self.view addSubview: subView];

UPDATE: definition for subView:

@interface PreferencesViewController : UIViewController  {

    UIView *subView;

@property (nonatomic, retain)  UIView *subView;

2012-04-04 19:28
by SpokaneDude
What is subView? Is it defined somewhere - Adam Shiemke 2012-04-04 19:41
Question updated.. - SpokaneDude 2012-04-04 19:42
I created a test project with a storyboard (Xcode 4.2, SDK 5.0) and pasted in your code: no problem. Try putting a breakpoint on Objective-C exceptions, or catching the exception, and seeing what the stack symbols look like - Phillip Mills 2012-04-04 20:20


The problem was the UIViewController was farkled...don't know how, but once it was replaced, it worked like a champ! Thank you all for your responses...

2012-04-04 22:14
by SpokaneDude


That really should work. Was your view controller (PreferencesViewController) properly alloc'd and init'd? Did you @synthesize your subview?

Although it shouldn't matter, you could try using floats for the CGRect (add a .0 to the end of each).

2012-04-04 19:40
by Adam Shiemke
Hi Adam... yes, subView was @synthesiz'ed... floats made no difference...what about it being XCode4 with storyboards? And I know it's getting to the PreferencesViewController because that's where the code resides... I wonder if it's a XCode4 bug - SpokaneDude 2012-04-04 20:11
ADam... go to yesterdays Q(http://stackoverflow.com/questions/10015985/how-to-move-this-colorpicker-from-iphone-to-a-portion-of-ipad-scene): and see my last comment.. - SpokaneDude 2012-04-04 20:12


Try moving your sub view instantiation code to the method viewWillAppear of your main view. This guarantees everything has been initialized.

2012-04-04 21:05
by Chris Grundy