Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Example of [NSDictionary getObjects:andKeys:]

I couldn't find a working example of the method [NSDictionary getObjects:andKeys:]. The only example I could find, doesn't compile. I provided the errors/warnings here in case someone is searching for them.

The reason I was confused is because most methods on NSDictionary return an NSArray. However, in the documentation it states that the out variables of this method are returned as C arrays.

Here are the error messages/warnings you might get if you follow the linked example:

NSDictionary *myDictionary = ...;

id objects[]; // Error: Array size missing in 'objects'
id keys[]; // Error: Array size missing in 'keys'

[myDictionary getObjects:&objects andKeys:&keys];

for (int i = 0; i < count; i++) {
  id obj = objects[i];
  id key = keys[i];
}

.

NSDictionary *myDictionary = ...;

NSInteger count = [myDictionary count];
id objects[count];
id keys[count];
[myDictionary getObjects:&objects andKeys:&keys]; // Warning: Passing argument 1 of 'getObjects:andKeys:' from incompatible pointer type.

for (int i = 0; i < count; i++) {
  id obj = objects[i];
  id key = keys[i];
}

I'll provide a working solution as an answer to this question.

like image 585
Senseful Avatar asked May 24 '10 00:05

Senseful


2 Answers

Here's the correct way to use this method:

NSDictionary *myDictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"1", @"A", @"2", @"B", nil];

NSInteger count = [myDictionary count];
id objects[count];
id keys[count];
[myDictionary getObjects:objects andKeys:keys];

for (int i = 0; i < count; i++) {
  id obj = objects[i];
  id key = keys[i];
  NSLog(@"%@ -> %@", obj, key);
}
like image 65
Senseful Avatar answered Oct 24 '22 21:10

Senseful


Under ARC the solution needs to be modified as follows (__unsafe_unretained added to the array definitions):

NSDictionary *myDictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"1", @"A", @"2", @"B", nil];

NSInteger count = [myDictionary count];
id __unsafe_unretained objects[count];
id __unsafe_unretained keys[count];
[myDictionary getObjects:objects andKeys:keys];

for (int i = 0; i < count; i++) {
  id obj = objects[i];
  id key = keys[i];
  NSLog(@"%@ -> %@", obj, key);
}
like image 36
Peter Avatar answered Oct 24 '22 22:10

Peter