在使用可变数组创建字典时,我在理解内存管理时遇到了问题。我正在使用 ios6 SDK 和部署目标 5.1。
在“Group”类的实现中,“namesAndEmails”方法构建了一个数组“emails”,其中包含带有电子邮件的 Person 对象的电子邮件地址。如果 Person 对象没有电子邮件,则将 Person 名称添加到另一个数组“namesWithNoEmail”。数组在字典中返回。
#import "Group.h"
@implementation Group
-(NSDictionary*) namesAndEmails {
NSMutableArray *emails = [[NSMutableArray alloc] initWithCapacity:0] ;
NSMutableArray *namesWithNoEmail = [[NSMutableArray alloc] initWithCapacity:0];
NSString *email;
NSString *name;
for (Person *p in allPersons) {
email = p.email;
name = p.name;
if ([email length]==0) {
[namesWithNoEmail addObject:name];
} else {
[emails addObject:email];
}
}
NSArray *keys = [NSArray arrayWithObjects:@"emails",@"names", nil];
NSArray *objects = [NSArray arrayWithObjects:emails, namesWithNoEmail, nil];
//[emails release];
//[namesWithNoEmail release];
return [NSDictionary dictionaryWithObjects:objects forKeys:keys];
}
在代码中的其他地方,我希望向一组人发送电子邮件,因此我调用 emailGroup 方法,该方法通过在组中调用“namesAndEmails”来获取字典。
-(void) emailGroup:(Group*) g {
NSDictionary *emailInfo = [g namesAndEmails];
guestsWithNoEmail = [emailInfo objectForKey:@"names"];
guestEmails = [emailInfo objectForKey:@"emails"];
int nGuestsWithNoEmail = [guestsWithNoEmail count];
if (nGuestsWithNoEmail > 0) {
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"No emails" message:@"" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
[alert show];
}
// some more code here
MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject:subject];
[picker setMessageBody:@"" isHTML:NO];
[picker setToRecipients:guestEmails];
[[self delegate ] presentModalViewController:picker animated:YES];
[picker release];
}
据我了解,“namesAndEmails”中的 [NSDictionary dictionaryWithObjects:objects forKeys:keys] 返回一个自动发布的字典。但是,如果我释放“emails”和“namesWithNoEmail”数组,为什么我的代码会崩溃?我认为字典在添加数组后将拥有数组的所有权,因此在方法中释放数组是安全的。我想这是不正确的,但为什么呢?
这样做是一种更干净的方式吗?感谢您的任何建议!