我有以下代码:
@implementation SendMapViewController
NSMutableArray *emails;
在这个方法中,我创建了电子邮件数组,并添加了一些NSStrings:
- (BOOL) peoplePickerNavigationController: (ABPeoplePickerNavigationController *)peoplePicker
shouldContinueAfterSelectingPerson: (ABRecordRef)person {
ABMultiValueRef emailInfo = ABRecordCopyValue(person, kABPersonEmailProperty);
NSUInteger emailCount = ABMultiValueGetCount(emailInfo);
if (emailCount > 1) {
UIActionSheet *emailsAlert = [[UIActionSheet alloc]
initWithTitle:@"Select an email"
delegate:self
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:nil];
emails = [NSMutableArray arrayWithCapacity: emailCount];
for (NSUInteger i = 0; i < emailCount; i++) {
NSString *emailFromContact = (NSString *)ABMultiValueCopyValueAtIndex(emailInfo, i);
[emails addObject: emailFromContact];
[emailsAlert addButtonWithTitle:emailFromContact];
[emailFromContact release];
}
[emailsAlert addButtonWithTitle:@"Cancel"];
[emailsAlert showInView:self.view];
[emailsAlert release];
}
else {
...
}
CFRelease(emailInfo);
[self dismissModalViewControllerAnimated:YES];
return NO;
}
正如您在代码中看到的,如果我展示了多个电子邮件和UIActionSheet。当用户点击代表和发送电子邮件的按钮时,我想执行以下代码:
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
if ([emails count] >= buttonIndex) {
NSString *contactEmail = (NSString *)[emails objectAtIndex:buttonIndex];
...
}
}
但是电子邮件阵列没有收到任何电子邮件。我做错了什么?
我正在为iPhone开发。
答案 0 :(得分:0)
当你不看时,你的emails
物体可能是自动释放的。替换行:
emails = [NSMutableArray arrayWithCapacity: emailCount];
使用:
[emails release];
emails = [[NSMutableArray alloc] initWithCapacity:emailCount];
以便emails
不会自动释放。 (记住,你拥有init
返回的任何内容,但是方便构造函数(如arrayWithCapacity:
返回的对象会自动释放。)
最佳解决方案是声明属性:
@property (retain) NSMutableArray* emails;
然后使用:
[self setEmails:[NSMutableArray arrayWithCapacity: emailCount]];
使用属性的第二种方法确实是最好的,因为它更灵活,更清晰。这样,属性的访问者(使用@synthesize
创建)将为您处理调用retain
。