传递给“menuItem”方法的指针是alloc,而对于“Pointer Inside”,则注册一个值。但对于“指针外”,价值是“空”......为什么?我传入了指针,它应该在方法中修改过了吗?
在头文件中:
UIButton *bMenu_time;
UILabel *lMenu_time;
实现:
- (void) menuItem: (UIView*)vMenu menuButton:(UIButton*)bMenu menuLabel: (UILabel*)lMenu menuPosX: (double)posX menuLenX: (double)lenX menuTagNum: (int)tagNum menuText: (NSString*)txtMenu{
bMenu = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[bMenu setFrame:CGRectMake(posX,0,lenX,25)];
[bMenu setTag: tagNum];
[bMenu addTarget:pSelf action:@selector(NewNumber:) forControlEvents:UIControlEventTouchUpInside];
[vMenu addSubview:bMenu];
lMenu = [[UILabel alloc] initWithFrame:CGRectMake(posX,0,lenX,25)];
[lMenu setBackgroundColor:[UIColor lightGrayColor]];
[lMenu setText:[NSString stringWithFormat: txtMenu]];
[lMenu setFont:[UIFont systemFontOfSize:14 ]];
[lMenu setTextAlignment:UITextAlignmentCenter];
[vMenu addSubview: lMenu];
NSLog(@"\nPointer Inside: %@\n", lMenu); // <--------- INSIDE WORKS
}
- (void) menuBuild{
pSelf = self;
theString = @"";
vMenu = [[UIView alloc] initWithFrame:CGRectMake(0,0,320,25)];
[pSelf.view addSubview:vMenu];
[vMenu setBackgroundColor:[UIColor grayColor]];
iTime = 2;
[self menuItem:vMenu menuButton:bMenu_time menuLabel:lMenu_time menuPosX:240+20 menuLenX:60 menuTagNum:102 menuText:[NSString stringWithFormat: @"Hold: %d", iTime]];
NSLog(@"\nPointer Outside: %@\n", lMenu_time); // <----- OUTSIDE is NULL ??
}
答案 0 :(得分:1)
目标C,与C一样,是通过值传递的。这意味着,如果你想通过将指针传递给函数来更改指针,则需要将指针传递给指针并使用它
在C中,这将是:
void alloc128 (void **ptr) {
*ptr = malloc (128);
}
将其映射到您的具体案例,您可以:
menuBuild
以传递您要更改的内容的地址。答案 1 :(得分:0)
paxdiablo是绝对正确的,但是如果您不确定传递引用的语法,那么您的代码应该是:
- (void) menuItem: (UIView*)vMenu menuButton:(UIButton **)bMenu menuLabel: (UILabel **)lMenu menuPosX: (double)posX menuLenX: (double)lenX menuTagNum: (int)tagNum menuText: (NSString*)txtMenu{
*bMenu = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[*bMenu setFrame:CGRectMake(posX,0,lenX,25)];
[*bMenu setTag: tagNum];
[*bMenu addTarget:pSelf action:@selector(NewNumber:) forControlEvents:UIControlEventTouchUpInside];
[vMenu addSubview:*bMenu];
*lMenu = [[UILabel alloc] initWithFrame:CGRectMake(posX,0,lenX,25)];
[*lMenu setBackgroundColor:[UIColor lightGrayColor]];
[*lMenu setText:[NSString stringWithFormat: txtMenu]];
[*lMenu setFont:[UIFont systemFontOfSize:14 ]];
[*lMenu setTextAlignment:UITextAlignmentCenter];
[vMenu addSubview: *lMenu];
NSLog(@"\nPointer Inside: %@\n", *lMenu); // <--------- INSIDE WORKS
}
- (void) menuBuild{
pSelf = self;
theString = @"";
vMenu = [[UIView alloc] initWithFrame:CGRectMake(0,0,320,25)];
[pSelf.view addSubview:vMenu];
[vMenu setBackgroundColor:[UIColor grayColor]];
iTime = 2;
[self menuItem:vMenu menuButton:&bMenu_time menuLabel:&lMenu_time menuPosX:240+20 menuLenX:60 menuTagNum:102 menuText:[NSString stringWithFormat: @"Hold: %d", iTime]];
NSLog(@"\nPointer Outside: %@\n", lMenu_time); // <----- OUTSIDE is NULL ??
}
注意事项:
了解iOS如何在NSString initWithContentsOfFile等方法中使用错误参数:error:有关如何使用此方法的更多示例。