开发者

Error with NSDictionary

I am trying to generate an UIActionSheet from a NSDictionary.

codeCountryMap is NSDictionary variable defined in .h file. The code compiled correctly but crashes on run time. But the whole code works when the initialization is done in the handleEvents method

- (void)viewDidLoad {
   [super viewDidLoad];
    NSArray *codes = [NSArray arrayWithObjects:@"91", @"01", @"002", nil];
    NSArray *cName = [NSArray arrayWithObjects:@"ABC", @"QWE", @"XYZ", nil];
    codeCountryMap = [NSDictionary dictionaryWithObjects:codes forKeys:cName];
}

-(IBAction) handleEvents:(id)sender
{       
    UIActionSheet *displayCodeCountryMap = [[UIActionSheet alloc] initWithTitle:@"Select Country" delegate:self cancelButtonTitle:nil 
                                          destructiveButtonTitle:nil 开发者_开发技巧otherButtonTitles:nil,nil];

    for(id key in codeCountryMap) {
        [displayCodeCountryMap addButtonWithTitle:(NSString *)key];
    }

    [displayCodeCountryMap addButtonWithTitle:@"Cancel"];
    displayCodeCountryMap.cancelButtonIndex = [codeCountryMap count];
    displayCodeCountryMap.actionSheetStyle = UIActionSheetStyleBlackOpaque;
    [displayCodeCountryMap showInView:self.view];
    [displayCodeCountryMap release];
    [country resignFirstResponder];
}

The app crashes when the handleEvents: method is called. Any kind of help would be greatly appriciated.

Thanks in advance.


This more than likely is a memory management issue. It looks like you are setting the iVar codeCountryMap to an autoreleased object of NSDictionary and not retaining it(at least not in this code snippet). This means that when the 'handleEvents' method is called the NSDictionary item has been released from memory.

Try either retaining the NSDictionary item or, if codeCountryMap is defined as a retained property, then use the following code to set it.

self.codeContryMap = [NSDictionary dictionaryWithObjects:codes forKeys:cName];

This will use the synthesized methods to set the property and retain it.


No need for 2 nils terminators in the otherButtonTitles argument. If you had passed in strings then it would have to be nil terminated. Since you did not, one nil is enough.

UIActionSheet *displayCodeCountryMap = [[UIActionSheet alloc] initWithTitle:@"Select Country" delegate:self cancelButtonTitle:nil 
                                          destructiveButtonTitle:nil otherButtonTitles:nil];
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜