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.
I would have created a simple NSObject class for Agent:
// Agent.h
@interface Agent : NSObject
@property (nonatomic, copy) NSString *agentName;
- (id)initWithAgentName:(NSString *)name;
@end
// Agent.m
@implementation Agent
- (id)initWithAgentName:(NSString *)name
{
self = [super init];
if (self) {
// Custom initialization
self.agentName = name;
}
return self;
}
And then create instances like:
// Assuming dictArray contains NSDictionaries like your code implies
for (id dictionary in dictArray)
{
NSString *agentName = [dictionary objectForKey:@"name"];
Agent *agent = [[Agent alloc] initWithAgentName:agentName];
[self.myAgents addObject:agent];
}
精彩评论