0

I alloc a viewcontroller without init it, but everything works fine. The subviews in the viewcontroller work fine.

Here is the code.

self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
[self.window makeKeyAndVisible];
self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:[ViewController alloc]];

The code in ViewController.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self test];
}


- (void)test
{
    self.view.backgroundColor = [UIColor whiteColor];
    CGRect frame = CGRectMake( 50, 100, 200, 200);
    UIScrollView *scrollView= [[UIScrollView alloc] initWithFrame:frame];
    [self.view addSubview:scrollView];
    frame= CGRectMake( 0, 0, 500, 500);
    UIImageView *myImageView= [[UIImageView alloc] initWithFrame:frame];
    [scrollView addSubview:myImageView];
    scrollView.contentSize = CGSizeMake(500,500);

    scrollView.backgroundColor = [UIColor blackColor];
    myImageView.backgroundColor = [UIColor yellowColor];

    scrollView.contentOffset = CGPointMake(0, 0);

}


@end
Zentopia
  • 735
  • 1
  • 8
  • 14

1 Answers1

0

Avi got it right in (his?) comment. It's dumb luck. This is like saying "I've been driving my car for 30,000 km without changing the oil and it's running fine. Why does everybody say you have to change your oil?"

Init does the setup for a class, and it's ancestor classes. It's fairly certain that there is some setup that isn't getting done that will cause problems in the future.

The proper way to create an object is with alloc/init. If you don't do that, "the result is undefined."

Duncan C
  • 128,072
  • 22
  • 173
  • 272