开发者

Accessing ViewController's variables from UIActionSheet delegate

I have the following code:

@implementation SendMapViewController

NSMutableArray *emails;

At this method I create emails array and I add some 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;
}

As you can see开发者_JAVA百科 in code, if there are more than one email I show and UIActionSheet. When user clicks on a button representing and email, I want to execute the following code:

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {

    if ([emails count] >= buttonIndex) {
        NSString *contactEmail = (NSString *)[emails objectAtIndex:buttonIndex];

        ...
    }
}

But emails array hasn't got any email. What I'm doing wrong?

I'm developing for iPhone.


Your emails object was probably autoreleased when you weren't looking. Replace the line:

emails = [NSMutableArray arrayWithCapacity: emailCount];

with:

[emails release];
emails = [[NSMutableArray alloc] initWithCapacity:emailCount];

so that emails is not autoreleased. (Remember, you own anything returned by init, but objects returned by convenience constructors like arrayWithCapacity: come autoreleased.)

The best solution is to declare a property:

@property (retain) NSMutableArray* emails;

and then use:

[self setEmails:[NSMutableArray arrayWithCapacity: emailCount]];

This second method, using a property, is really the best, because it is more flexible and clear. This way, the property's accessors (which you create with @synthesize) will handle calling retain for you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜