Search code examples
objective-cxcodeiphone-sdk-3.0nsinvocation

Does nsinvocation invoked?


I'am a newby in objective c and iphone developing. I confused. I trying to create button that are created at the runtime,after clicking another button,and application doesn't know it:

 -(void)button4Pushed{
    NSLog(@"Button 4 pushed\n");
    Class cls = NSClassFromString(@"UIButton");//if exists {define class},else cls=nil
    id pushButton5 = [[cls alloc] init];

    CGRect rect =CGRectMake(20,220,280,30);
    NSValue *rectValue = [NSValue valueWithCGRect:rect];


    //--------------1st try set frame  - work,but appears at wrong place
    //[pushButton5 performSelector:@selector(setFrame:) withObject:rectValue];
    //--------------2nd try set frame  + this work correctly
    [pushButton5 setFrame: CGRectMake(20,220,280,30)];                    



    //this work correct [pushButton5 performSelector:@selector(setTitle:forState:) withObject:@"5th Button created by 4th" withObject:UIControlStateNormal];
    //but i need to use invocation to pass different parameters:

    NSMethodSignature *msignature;
    NSInvocation *anInvocation;

    msignature = [pushButton5 methodSignatureForSelector:@selector(setTitle:forState:)];
    anInvocation = [NSInvocation invocationWithMethodSignature:msignature];

    [anInvocation setTarget:pushButton5];
    [anInvocation setSelector:@selector(setTitle:forState:)];

    NSNumber* uicsn =[NSNumber numberWithUnsignedInt:UIControlStateNormal];
    NSString *buttonTitle = @"5thbutton";

    [anInvocation setArgument:&buttonTitle atIndex:2];
    [anInvocation setArgument:&uicsn atIndex:3];
    [anInvocation retainArguments];
    [anInvocation invoke];

    [self.view addSubview:(UIButton*)pushButton5];
}

What am I doing wrong? Invocation is invoked, but there is no result... I know that I can create it this way:

    UIButton *pushButton3 = [[UIButton alloc] init];
    [pushButton3 setFrame: CGRectMake(20, 140, 280, 30)];
    [pushButton3 setTitle:@"I'm 3rd button!created by 2nd" forState:UIControlStateNormal];
    [self.view addSubview:pushButton3];

But I need to use invocation, and don't know why does it not working?

Thanks for your help.


Solution

  • Your setting an NSNumber * as your second argument, but the method you are trying to invoke (effectively) requires an int. Use your exact same code but try these lines instead:

    UIControlState uicsn = UIControlStateNormal;
    

    // then

    [anInvocation setArgument:&uicsn atIndex:3];