对象是在头文件中声明时分配和初始化的,还是我需要在我的实现中分配和初始化对象?
以下哪个是正确的?
.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 ];
}
或
.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 ];
}
最佳答案
对象属性在 Objective-C 中被显式设置为 nil
以避免其他语言可能存在的未初始化对象问题。
非对象属性设置为零版本(即 CGFloat
为 0.000000,NSRange
为 {0,0},BOOL
为否)。
因此,您的第二个代码是正确的,尽管如果您在 self.bgImageView.image = ...
(例如,在 View Controller 的 init
方法中或在 loadView
中,甚至在 self.bgImageView.image
上面的行中)。
关于ios - 如果在 .h 文件中声明,则需要分配和初始化对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17905888/