1

I have the following method definition:

- (id)initTestName: (NSString*) name andTime: (int) time, ...  {
    self = [super init];
    if (self) {
        _name = name;
        _time = time;

       //The method goes here
    }
    return self;
}

Each argument that comes after time is going to be a String. I need to define a method inside the initiator that takes each of the passed arguments (could be any number), and then create an array of String objects where each object is a single String argument. The question "How to create argument methods in Objective C" doesn't show how to create that loop. I really appreciate if you consider that I am very new to coding before you denounce my question and block me from asking anymore.

Alex R
  • 51
  • 5
  • 1
    Possible duplicate of [How to create variable argument methods in Objective-C](https://stackoverflow.com/questions/4804674/how-to-create-variable-argument-methods-in-objective-c) – dan Apr 22 '19 at 23:40
  • *"The question "How to create argument methods in Objective C" doesn't show how to create that loop"* - yes it does. Look at all of the answers. – rmaddy Apr 22 '19 at 23:50
  • Thanks, I'm still not able to figure it out. I'd rather wait for someone who's willing to just answer my question. – Alex R Apr 22 '19 at 23:57
  • 2
    If you included some code from where you attempted to use the answers in the linked question and explained what issues you had with it then it would be easier to find someone to help you. – dan Apr 23 '19 at 00:02

1 Answers1

1

Here's a little bit of a more detailed answer: Since your arguments are going to be Strings, you have to add at least one to the method definition:

- (id)initTestName: (NSString*) name andTime: (int) time andArg:(NSString*) arg, ...

Then we need to use va_List which consist of four macros:

1) Pointer that will be used to point to the first element of the variable argument list.

va_list listPointer;

2) Now, we make listPointer point to the first argument in the list

va_start( listPointer, arg );

3) Next, we're going to start to actually retrieving the values from the "va_list" itself:

    NSMutableArray argsArray;
    for( int i = 0; i < arg; i++ ) {
        [argsArray addObject:va_arg(listPointer, NSString*);    
}

4) finally, clean up by saying va_end() :

va_end(listPointer);
Fady E
  • 346
  • 3
  • 16