我正在使用以下方法开发iPhone应用程序:
- (void)drawView:(ARCoordinate *)coordinate {
UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, BOX_WIDTH, 20.0)];
[titleLabel setBackgroundColor: [UIColor colorWithWhite:.3 alpha:.8]];
[titleLabel setTextColor: [UIColor whiteColor]];
[titleLabel setTextAlignment: UITextAlignmentCenter];
[titleLabel setText: [coordinate title]];
[titleLabel sizeToFit];
[titleLabel setFrame: CGRectMake(BOX_WIDTH / 2.0 - [titleLabel bounds].size.width / 2.0 - 4.0,
0,
[titleLabel bounds].size.width + 8.0,
[titleLabel bounds].size.height + 8.0)];
UILabel *subTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, BOX_WIDTH, 20.0)];
[subTitleLabel setBackgroundColor: [UIColor colorWithWhite:.3 alpha:.8]];
[subTitleLabel setTextColor: [UIColor whiteColor]];
[subTitleLabel setTextAlignment: UITextAlignmentCenter];
[subTitleLabel setText: [coordinate subtitle]];
[subTitleLabel sizeToFit];
[subTitleLabel setFrame: CGRectMake(BOX_WIDTH / 2.0 - [subTitleLabel bounds].size.width / 2.0 - 4.0,
21.0,
[subTitleLabel bounds].size.width + 8.0,
[subTitleLabel bounds].size.height + 8.0)];
UIImageView *pointView = [[UIImageView alloc] initWithFrame:CGRectZero];
[pointView setImage: [UIImage imageNamed:@"location.png"]];
[pointView setFrame: CGRectMake((int)(BOX_WIDTH / 2.0 - [pointView image].size.width / 2.0),
(int)(BOX_HEIGHT / 2.0 - [pointView image].size.height / 2.0),
[pointView image].size.width, [pointView image].size.height)];
[self addSubview:titleLabel];
[self addSubview:subTitleLabel];
[self addSubview:pointView];
self.backgroundColor = [UIColor clearColor];
}
此代码运行良好,编译器不会抱怨它。但我不确定为什么我不必做以下事情:
[titleLabel release];
[subTitleLabel release];
[pointView release];
我认为,是由于这些视图被添加到另一个视图(此方法位于从View继承的类中)。
[self addSubview:titleLabel];
[self addSubview:subTitleLabel];
[self addSubview:pointView];
有什么建议吗?
答案 0 :(得分:1)
为了避免内存泄漏,您应该在将这些视图添加为子视图后将其释放!
[self addSubview:titleLabel];
[self addSubview:subTitleLabel];
[self addSubview:pointView];
[titleLabel release];
[subTitleLabel release];
[pointView release];
答案 1 :(得分:0)
这取决于。您是否在iOS 5上使用自动引用计数执行此操作?然后你不再需要打电话了。
如果您使用的是iOS 4或不使用ARC,那么如果您不进行发布,编译器不会抱怨,但您的代码肯定会泄漏内存。
尝试通过Xcode Analyzer运行此代码,该代码应指向您。