如何使用nil终止的params列表在init方法中调用super?

时间:2012-05-28 10:38:07

标签: objective-c cocoa

我是UIAlertView的子类。我想用以下签名实现一个init方法:

- (id)initWithTitle:(NSString *)title 
            message:(NSString *)message
         identifier:(NSInteger)ident
           delegate:(id)delegate 
  cancelButtonTitle:(NSString *)cancelButtonTitle 
  otherButtonTitles:(NSString *)otherButtonTitles,...

它只是默认的UIAlertView方法,添加了参数identifier

- (id)initWithTitle:(NSString *)title 
            message:(NSString *)message
           delegate:(id)delegate 
  cancelButtonTitle:(NSString *)cancelButtonTitle 
  otherButtonTitles:(NSString *)otherButtonTitles,...

如果我在编译时不知道我的init方法otherButtonTitles参数将是什么,那么现在调用super方法的正确语法是什么?

self = [super initWithTitle:title
                    message:message
                   delegate:delegate
          cancelButtonTitle:cancelButtonTitle 
          otherButtonTitles:otherButtonTitles, nil];
//I will only get the first param with this syntax

2 个答案:

答案 0 :(得分:1)

首先,了解可变参数函数,它可以帮助您:Wikipedia

Example:
#include <stdarg.h>

void logObjects(id firstObject, ...) // <-- there is always at least one arg, "nil", so this is valid, even for "empty" list
{
  va_list args;
  va_start(args, firstObject);
  id obj;
  for (obj = firstObject; obj != nil; obj = va_arg(args, id)) // we assume that all arguments are objects
    NSLog(@"%@", obj);
  va_end(args);
}

其次,最好建立一个 Objectve-C类而不是子类UIAlertView

Example:
@interface UIAlertView(Identifiers)
- (id)initWithTitle:(NSString *)title 
            message:(NSString *)message
         identifier:(NSInteger)ident
           delegate:(id)delegate 
  cancelButtonTitle:(NSString *)cancelButtonTitle 
  otherButtonTitles:(NSString *)otherButtonTitles,...;
@end

答案 1 :(得分:0)

文档说

  

子类注释
  UIAlertView类旨在按原样使用,不支持子类化。此类的视图层次结构是私有的,不得修改。

但到目前为止,我认为你无法做到。您始终可以通过实现普通init然后使用传入的参数配置对象来重新创建此便捷方法。