XJo*_*nes 4 iphone variables methods arguments objective-c
OS X Developer Library显示了如何在以下技术文章中创建一个采用可变数量args的方法:http://developer.apple.com/library/mac/#qa/qa1405/_index.html.
我试图弄清楚是否可以继承现有的方法实现,该方法采用变量args并调用超类实现.
以UIActionSheet为例,请看下面的代码.调用超类initWithTitle方法只传递第一个'otherButtonTitle'.我不知道如何传递变量参数列表中包含的其余字符串.
// MyActionSheet.m
- (id)initWithTitle:(NSString *)title
delegate:(id < UIActionSheetDelegate >)delegate
cancelButtonTitle:(NSString *)cancelButtonTitle
destructiveButtonTitle:(NSString *)destructiveButtonTitle
otherButtonTitles:(NSString *)otherButtonTitles, ...
{
// this calls the superclass initWithTitle: method but does not
// pass NIL terminated list of strings
self = [super initWithTitle:title
delegate:delegate
cancelButtonTitle:cancelButtonTitle
destructiveButtonTitle:destructiveButtonTitle
otherButtonTitles:otherButtonTitles, nil];
if (self) {
// custom initialization
}
return self;
}
Run Code Online (Sandbox Code Playgroud)
我可以使用va_list,va_start,va_end获取args,但不知道如何将它们传递给超类方法.
万一有人试图告诉我,我可以用不同的方式做到这一点(例如,不要传递变量args但是使用va_list,va_start,va_end创建一个字符串数组并调用addButtonWithTitle:多次,我知道我可以我用UIActionSheet作为例子.在其他情况下,使用变量args对方法进行子类化的能力将是有用的,我想学习如何做到我所问的是否可行.
谢谢!
Cocoa中的许多类都有采用可变数量参数的方法.在大多数情况下,这些类也将具有采用va_list的等效方法.如果您正在使用的课程提供其中一种方法,则只能按照您的建议行事.例如,+ [NSString stringWithFormat:...]采用可变数量的参数.Cocoa提供 - [NSString initWithFormat:arguments:]其中arguments参数是va_list.这允许您执行以下操作:
- (void)setContentsWithFormat:(NSString *)formatString, ... {
[contents autorelease];
va_list args;
va_start(args, formatString);
contents = [[NSString alloc] initWithFormat:formatString arguments:args];
va_end(args);
}
Run Code Online (Sandbox Code Playgroud)
va_list参数允许我们将自己的变量参数列表传递给Cocoa方法,以便Cocoa方法可以处理参数.
但是,由于UIAlertView不提供va_list API,最简单的方法可能是重复调用addButtonWithTitle:
| 归档时间: |
|
| 查看次数: |
1367 次 |
| 最近记录: |