Andy
Andy

Reputation: 27

What is the equivalent of php array() in objective-c

How can I do this:

PHP:

$arr1 = array( 'a', 1, 'b', 5, 'z' );
$arr2 = array( 'key1' => 'value1', 'key2' => 'value2' );
$arr3 = array( 'key1' => 'value1', 'value2', 'value3' );

and this:

foreach ($arr1 as $value) {
    echo "Value: $value<br />\n";
}
foreach ($arr2 as $key => $value) {
    echo "Key: $key; Value: $value<br />\n";
}

In Objective-C ?


Thank you

Upvotes: 1

Views: 620

Answers (2)

sksamuel
sksamuel

Reputation: 16387

For an array

  NSMutableArray *arr1 = [NSMutableArray arrayWithObjects:@"1", @"2", @"a", @"b", nil];
    for (NSString *obj in arr1) {
        // do stuff
    }

And for a map

  NSMutableArray *keys = [NSMutableArray arrayWithObjects:@"1", @"2", @"3", @"4", nil];
    NSMutableArray *values = [NSMutableArray arrayWithObjects:@"a", @"b", @"c", @"d", nil];
    NSDictionary *dict = [NSDictionary dictionaryWithObjects:keys forKeys:values];
    for (id key in dict) {
        id value = [dict valueForKey:key];
        // do stuff with value
    }

Upvotes: 0

Jhaliya - Praveen Sharma
Jhaliya - Praveen Sharma

Reputation: 31720

$arr1 --- > NSArray Or NSMutabelArray

$arr2 --- > NSDictionary or NSMutabelDictionary.

See accessing values from NSDirectiory.

NSDirectiory* arr2;
for (NSString* myKey in arr2)
{
    id value = [arr2 objectForKey:myKey];
}

See accessing values from NSMutableArray.

NSMutableArray * arr1;
for (id* object in arr1) {
  //id hold the value of your object stored in array.
}

Upvotes: 2

Related Questions