gpt4 book ai didi

objective-c - 如何在带有 nil 终止参数列表的 init 方法中调用 super ?

转载 作者:行者123 更新时间:2023-12-03 17:57:45 25 4
gpt4 key购买 nike

我正在继承 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

最佳答案

首先,了解一下可变参数函数,它可以帮助你: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

关于objective-c - 如何在带有 nil 终止参数列表的 init 方法中调用 super ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10783221/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com