gpt4 book ai didi

iphone - 将 UIImageView 存储在 NSMutableDictionary 中

转载 作者:行者123 更新时间:2023-11-29 04:51:02 24 4
gpt4 key购买 nike

我有一个简单的问题。这是我的头文件:

#import <UIKit/UIKit.h>

@interface FirstFaceController : UIViewController

@property (nonatomic,retain) NSMutableDictionary *face1Layers;

@end

这个.m,我在这里初始化我的字典并将其放在 UIImageView 的位置:

#import "FirstFaceController.h"

@implementation FirstFaceController

@synthesize face1Layers;



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

- (void)viewDidLoad
{
[super viewDidLoad];

self.face1Layers = [NSMutableDictionary dictionary];
[self.face1Layers setObject:
[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pic.png"]]
forKey:@"pic"];

[self.view addSubview:[self.face1Layers objectForKey:@"pic"]];
if ( [[face1Layers objectForKey:@"pic"] superview] == nil ) {
//....
}
}

然后我调用 [[face1Layers objectForKey:@"pic"] superview] 我有“EXC_BAD_ACCESS”。为什么?

最佳答案

尝试这样做:

NSMutableDictionary* tempDict = [[NSMutableDictionary alloc] init];
self.face1Layers = tempDict;
UIImageView* picView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pic.png"]];
[self.face1Layers setObject:picView forKey:@"pic"];
[picView release];
[tempDict release];

不要通过一行代码创建和插入您的 NSMutableDictionaryUIImageView,因为存在泄漏。

在第一种情况下,如果执行以下操作,则保留计数为 2。 face1Layers 有保留策略。

self.face1Layers = [[NSMutableDictionary alloc] init];

您可以避免像我之前解释的那样拆分代码,或者向初始化的对象发送一条 autorelease 消息。

在第二种情况下,当您在 NSDictionaryNSArray (及其子类)中添加对象时,这些类会保留添加的对象。

希望对您有所帮助。

关于iphone - 将 UIImageView 存储在 NSMutableDictionary 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8835634/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com