添加到数组的对象立即“超出范围”
我是 Objective C 的新手,我确实需要一些帮助。
我创建了一个名为 Agent 的类。 Agent 类包含以下方法:
+ (Agent *)agentWithName:(NSString*)theName {
Agent *agent = [[[Agent alloc] init] autorelease];
agent.agentName = theName;
return agent;
}
然后从我的根视图控制器中循环遍历名称字典,为每个名称创建一个 Agent 对象并将该 Agent 对象添加到 NSMutableArray 中:
for (id object in dictArray) {
NSString *agentName = [object objectForKey:@"name"];
[self.myAgents addObject:[Agent agentWithName:agentName]];
}
问题是一旦执行通过[self.myAgents addObject:[Agent agentWithName:agentName]];
,NSMutableArray self.myAgents
内的所有代理对象都被调试器列为“out of” 范围'。当我尝试访问该数组中的对象时,这会导致我的代码稍后出现 EXC_BAD_ACCESS 。对象被添加到数组中(至少它们显示在 XCode 调试器中),它们只是超出了范围,但在退出 for 循环之前它们就超出了范围。谁能解释一下我做错了什么吗?我几乎可以肯定这与我对内存管理缺乏了解有关。感谢您的关注。
I'm new to Objective C and I could really use some assistance.
I have created a class called Agent. The Agent class contains the following method:
+ (Agent *)agentWithName:(NSString*)theName {
Agent *agent = [[[Agent alloc] init] autorelease];
agent.agentName = theName;
return agent;
}
Then from my root view controller I want to loop through a Dictionary of names creating an Agent object for each name and adding that Agent object to an NSMutableArray:
for (id object in dictArray) {
NSString *agentName = [object objectForKey:@"name"];
[self.myAgents addObject:[Agent agentWithName:agentName]];
}
The trouble is that as soon as the execution has passed [self.myAgents addObject:[Agent agentWithName:agentName]];
, all the agent objects inside of the NSMutableArray self.myAgents
are listed by the debugger as 'out of scope'. This causes an EXC_BAD_ACCESS later in my code when I try to access objects in that array. Objects are getting added to the array (at least they're showing up in the XCode debugger) they're just out of scope, but they're out of scope before even exiting the for loop. Can anyone please explain what I'm doing wrong? I'm almost certain it has to do with my lack of understanding for memory management. Thanks for taking a look.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我会为 Agent 创建一个简单的 NSObject 类:
然后创建如下实例:
I would have created a simple NSObject class for Agent:
And then create instances like: