1

On assignment 2 of the Stanford CS193P course it states that I must add a runProgram class method with the following signature:

+ (double)runProgram:(id)program
usingVariableValues:(NSDictionary *)variableValues;

However I do not recognise or know how to use this syntax as up until now methods have been written more simply:

+ (double)performOperation:(NSString *)operation

Could someone explain this signature? Should the method be written on one line? How do I get/set my dictionary?

Sorry for the basic questions but I am a complete beginner!

Bugs
  • 21
  • 3

4 Answers4

1
+ (double)runProgram:(id)program
 usingVariableValues:(NSDictionary *)variableValues;

Is the same as:

+ (double)runProgram:(id)program usingVariableValues:(NSDictionary *)variableValues;

It is formatted on two lines for easier reading.

In this declaration, your selector is: runProgram:usingVariableValues:, and after colons are argument names with their types, i.e. program of type id and variableValues of type NSDictionary *.

You call it using

[ClassName runProgram:myProgram usingVariableValues:myVariables];

To create a dictionary, you use code like this:

NSDictionary *myDict = [NSDictionary dictionaryWithObjectsAndKeys:@"value1",
                        @"key1", @"value2", @"key2", nil];
Peter Štibraný
  • 32,463
  • 16
  • 90
  • 116
0

Should be on one line for readability:

+ (double)runProgram:(id)program usingVariableValues:(NSDictionary *)variableValues;

Usage is just as you would expect:

[MyCustomClass runProgram:myProgram usingVariableValues:myDictionary];
sosborn
  • 14,676
  • 2
  • 42
  • 46
0

Class method are not any new method, basic differences here - 1. In Signature of Method 2. Accessible by ClassName instead of Class Object

+ (double)runProgram:(id)program usingVariableValues:(NSDictionary *)variableValues;

is same as -

+ (double)runProgram:(id)program
 usingVariableValues:(NSDictionary *)variableValues;

While calling this method -

[ClassName runProgram:someProgram usingVariableValues:someVar];

or in formatted way -

[ClassName runProgram:someProgram 
  usingVariableValues:someVar];
rishi
  • 11,779
  • 4
  • 40
  • 59
0
+ (double)runProgram:(id)program usingVariableValues:(NSDictionary *)variableValues;

is simply a method taking two parameters, one of type id and one a dictionary. In Objective-C, parameters are interleaved into the selector. So to invoke this method you would do

[MyClass runProgram: aProgram usingVariableValues: aDictionary];

aDictionary is a dictionary you need to construct before invoking the method. The easiest way is to do this is to create a mutable dictionary and add the items one by one.

NSMutableDictionary* aDictionary = [[NSMutableDictionary alloc] init];
[aDictionary setObject: @"foo" forKey: @"bar"];
[aDictionary setObject: @"baz" forKey: @"fizz"];
// etc
JeremyP
  • 84,577
  • 15
  • 123
  • 161