【问题标题】:Memory leak when subclassing UIView子类化 UIView 时的内存泄漏
【发布时间】:2010-02-17 06:44:31
【问题描述】:

仅使用 UIView 的子类时出现内存泄漏。它泄漏了 128 个字节并一直向下通过 CoreGraphics 等。我的子类只是一个生成的骨架,其中没有任何内容。当我只使用 UIView 而不是 ScrollView 时,不会报告泄漏。它可能是什么,我错过了什么?

非常感谢, 亚历克斯。

======================================

//----  main.m

#import <UIKit/UIKit.h>

int main(int argc, char *argv[]) {

  //  NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    int retVal = UIApplicationMain(argc, argv, nil, @"testScrollViewAppDelegate");
  //  [pool release];
    return retVal;
}

//---testScrollViewAppDelegate.h

#import <UIKit/UIKit.h>

@interface testScrollViewAppDelegate : NSObject <UIApplicationDelegate> {
    UIWindow *window;
}

@property (nonatomic, retain) UIWindow *window;

@end


//--testScrollViewAppDelegate.m

#import "testScrollViewAppDelegate.h"
#import "ScrollView.h"

@implementation testScrollViewAppDelegate

@synthesize window;


- (void)applicationDidFinishLaunching:(UIApplication *)application {    

    window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    window.backgroundColor =  [UIColor whiteColor];

    CGRect frame =  CGRectMake(10, 150, 300, 200);
    ScrollView* scrollView = [[ScrollView alloc] initWithFrame:frame];

    [window addSubview:scrollView];

    [scrollView release],scrollView = nil;

    [window makeKeyAndVisible];
}


- (void)dealloc {
    [window release];
    [super dealloc];
}


@end

//-- ScrollView.h

#import <UIKit/UIKit.h>


@interface ScrollView : UIView {

}

@end


//-- ScrollView.m

#import "ScrollView.h"


@implementation ScrollView


- (id)initWithFrame:(CGRect)frame {

    if (self = [super initWithFrame:frame]) {
        // Initialization code
    }
    return self;

  }

- (void)drawRect:(CGRect)rect {
    // Drawing code
}

- (void)dealloc {
    [super dealloc];
}


@end

【问题讨论】:

    标签: iphone memory uiview subclass memory-leaks


    【解决方案1】:

    您为什么注释掉NSAutoreleasePool 代码?如果没有自动释放池,会导致大量的 ObjC 和 CF 对象被泄露。

    (另外,请告诉我们你是如何实现-drawRect:的。)

    【讨论】:

    • 发布时意外评论,因为我玩过不同的东西试图弄明白。 drawRect 中没有任何内容。我刚刚在 XCode 中创建了 UIView 的空子类。我在更大的应用程序中遇到了问题,这里只是尝试最小化测试示例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-19
    • 1970-01-01
    • 2011-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多