David Casillas
David Casillas

Reputation: 1911

How to call super in an init method with nil terminated list of params?

I am subclasing UIAlertView. I would like to implement a init method with the following signature:

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

It is just the default UIAlertView method with an added param identifier.

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

What is the correct syntax now to invoke the super method if I don't know in compile time what my init method otherButtonTitles params will be?

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

Upvotes: 0

Views: 170

Answers (2)

Oleg Trakhman
Oleg Trakhman

Reputation: 2082

First, Learn about variadic functions, it can help you: 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);
}

Second, it's better to make an Objectve-C Category rather than subclass 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

Upvotes: 1

Paul.s
Paul.s

Reputation: 38728

The docs say

Subclassing Notes
The UIAlertView class is intended to be used as-is and does not support subclassing. The view hierarchy for this class is private and must not be modified.

But to the point I don't think you can. You could always just recreate this convenience method by implementing a normal init and then configuring the object with the arguments passed in.

Upvotes: 0

Related Questions