0

在我的代码中:

*.h 文件

UIImageView*    imgFACE;
UIImage*        imgF;
UIImage*        imgG;

初始化:

imgF = [UIImage imageNamed: @"f.png"];
imgG = [UIImage imageNamed: @"g.png"];

UIImageView *img;
img = [[UIImageView alloc]initWithFrame:FACE_RECT];
[self addSubview:img];
self.imgFACE = img;
[img release];

在drawRect中,经常:

NSLog(@"[%@]", imgF);
if(something) self.imgFACE.image = imgF;
else          self.imgFACE.image = imgG;

NSLog 的标准结果是:

[<UIImage: 0x5db6b0>]

有时这个简单的代码会导致崩溃,NSLog 的结果很奇怪:

[Length 4 (2 blocks, 1 used, block 0 is at 0) 4 0x146d22c0 
{ NSColor =  "UIDeviceWhiteColorSpace 0 1"; 
  NSFont = "<UICTFont: 0x1454fc00> font-family: \".HelveticaNeueInterface-M3\"; 
  font-weight: normal; font-style: normal; font-size: 12.00pt"; 
  NSParagraphStyle = "Alignment 0, LineSpacing 0, ParagraphSpacing 0,
  ParagraphSpacingBefore 0, HeadIndent 0, TailIndent 0, FirstLineHeadIndent 0,
  LineHeight 0/0, LineHeightMultiple 0, LineBreakMode 4, Tabs (\n 28L,\n 56L,
  \n 84L,\n 112L,\n 140L,\n 168L,\n 196L,\n 224L,\n 252L,\n 280L,\n 308L,\n 336L\n),
  DefaultTabInterval 0, Blocks (null), Lists (null), BaseWritingDirection -1, 
  HyphenationFactor 0, TighteningFactor 0, HeaderLevel 0"; 
  NSShadow = "NSShadow {0, -1} color = {(null)}"; } 

什么是对象?

崩溃日志:

0libobjc.A.dylib 0x3b393b26 objc_msgSend + 5
1NOM2 0x000ad7a5 -[PanelInfoView myTimerMethod] (PanelInfoView.m:527) + 309157
2Foundation 0x319a3ecd __NSFireTimer + 64
3CoreFoundation 0x30f8b0e7 <redacted> + 14
4CoreFoundation 0x30f8acff <redacted> + 782
5CoreFoundation 0x30f8909b <redacted> + 1210
6CoreFoundation 0x30ef3ce7 CFRunLoopRunSpecific + 522
7CoreFoundation 0x30ef3acb CFRunLoopRunInMode + 106
8GraphicsServices 0x35c14283 GSEventRunModal + 138
9UIKit 0x33795a41 UIApplicationMain + 1136
10NOM2 0x0006e44d main (main.m:25) + 50253

我认为这是内存泄漏的结果。imgF & imgG 只初始化一次。

这个 UIImage 发生了什么?

4

1 回答 1

1
imgF = [UIImage imageNamed: @"f.png"];
imgG = [UIImage imageNamed: @"g.png"];

这两个都是自动释放的对象,

if(something) self.imgFACE.image = imgF;
else          self.imgFACE.image = imgG;

如果某些东西是 NO 则 imgG 会被 imgFACE 保留,如果你很幸运并且它还没有被释放,但是 imgF 仍然没有被任何人保留,所以在下一个 drawRect 很确定它会在 NSLog(@" [%@]", imgF) 或仅打印另一个对象,如果它幸运地分配在该地址上。

采用:

imgF = [[UIImage imageNamed: @"f.png"] retain];
imgG = [[UIImage imageNamed: @"g.png"] retain];

并在 dealloc 中释放它们:

- (void)dealloc {
     [imgF release];
     [imgG release];

     // cleanup other resources too

     [super dealloc];
}
于 2013-10-29T20:03:44.057 回答