1

我是objective c和iphone开发的新手。我很困惑。我试图创建在运行时创建的按钮,单击另一个按钮后,应用程序不知道它:

 -(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];
}

我究竟做错了什么?调用被调用,但没有结果......我知道我可以这样创建它:

    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];

但是我需要使用调用,不知道为什么它不起作用?

谢谢你的帮助。

4

2 回答 2

2

您将 NSNumber * 设置为您的第二个参数,但您尝试(有效)调用的方法需要一个 int。使用完全相同的代码,但请尝试以下几行:

UIControlState uicsn = UIControlStateNormal;

// 然后

[anInvocation setArgument:&uicsn atIndex:3];
于 2011-08-10T12:52:42.047 回答
1

为什么需要使用调用?

更新:根据用例,除非您不控制其他类,否则我会改用具有与此签名匹配的方法的协议,并收集对其进行合法调用的对象。

NSInvocation是运行时构建块/最后的类;如果您完全可以控制周围的对象,则应该使用其他可用的工具,例如协议(如果对象具有方法)和块或函数指针(如果您只想要脱离实体的函数)。

Perception 的答案解决了技术问题,但您可能会让事情变得更加复杂。

于 2011-08-10T11:50:17.523 回答