Search code examples
iosobjective-cnullnsarraynslog

How to acces an objects restoration id (why is it null?)


I have uiButtons in an xib. I have set restoration ids for all of them. I need to print a list of these restoration ids. to do this i call the following code in viewDidload:

-(void)loadViewFromNIB:(NSString *)nibName owner:(id)owner
{


NSArray *objects = [[NSBundle mainBundle] loadNibNamed:nibName owner:owner options:nil];
NSArray *subviews = [[objects objectAtIndex:0]subviews];
for (id key in subviews) {
        [key addTarget:self
        action:@selector(touchB:)
        forControlEvents:UIControlEventTouchDown];
        [key addTarget:self
                   action:@selector(touchE:)
         forControlEvents:UIControlEventTouchUpInside];
        NSString *ident = self.restorationIdentifier;
        NSLog(@"%@",ident);


}

i get this output:

2013-02-24 13:05:38.817 fozbKEY[3939:11603] (null)
2013-02-24 13:05:38.822 fozbKEY[3939:11603] (null)
2013-02-24 13:05:38.824 fozbKEY[3939:11603] (null)

this just repeats a bunch. What I am doing wrong? how do I fix it? Thanks!


Solution

  • You are logging the view controller's restoration id. Try logging the button's restoration id. Right now you do:

    NSString *ident = self.restorationIdentifier;
    

    Change that line to this:

    NSString *ident = [key restorationIdentifier];
    

    An even better change to your code would be this:

    for (UIView *subview in subviews) {
        if ([subview isKindOfClass:[UIButton class]]) {
            UIButton *key = (UIButton *)subview;
            [key addTarget:self action:@selector(touchB:) forControlEvents:UIControlEventTouchDown];
            [key addTarget:self action:@selector(touchE:) forControlEvents:UIControlEventTouchUpInside];
    
            NSString *ident = key.restorationIdentifier;
            NSLog(@"%@",ident);
        }
    }