Need to allocate and initialize object if declared in .h file

Is an object allocated and initialized when declared in header file or do I need to alloc and init the object in my implementation?

Which of these is correct?

.h

@interface myViewController : UIViewController

@property (nonatomic, strong) UIImageView *bgImageView;

@end 

.m
- (void)viewDidLoad
{
if (!self.bgImageView) {

        NSString *fullpath = [[[NSBundle mainBundle] bundlePath] stringByAppendingString:@"/Background.png"];

        self.bgImageView.image = [UIImage imageWithContentsOfFile:fullpath];

        [self.view addSubview:self.bgImageView ];
        [self.view sendSubviewToBack:self.bgImageView ];

}

or

.h

@interface myViewController : UIViewController

@property (nonatomic, strong) UIImageView *bgImageView;

@end 

.m 

- (void)viewDidLoad
{
if (!self.bgImageView) {

        NSString *fullpath = [[[NSBundle mainBundle] bundlePath] stringByAppendingString:@"/Background.png"];

        self.bgImageView = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:fullpath]];

        [self.view addSubview:self.bgImageView ];
        [self.view sendSubviewToBack:self.bgImageView ];

}

Upvotes: 0

Views: 369

Answers (2)

Kevin Low
Kevin Low

Reputation: 2682

Object properties are explicitly set to nil in Objective-C to avoid the uninitialized object issues that other languages can have.

Non-object properties are set to the zero version (i.e. CGFloat is 0.000000, NSRange is {0,0}, BOOL is NO).

Therefore, your second code is correct, although your first code would work if you had allocated and initialized self.bgImageView any time before self.bgImageView.image = ... (for example, in the init method of your view controller or in loadView or even the line above self.bgImageView.image).

Upvotes: 2

DogCoffee
DogCoffee

Reputation: 19946

Put alloc and init in the .m file, only put the @property in .h if some other VC needs to access the object, otherwise just have it in the .m as well.

Test your own code as well, best way to learn

Upvotes: 1

Related Questions