I needed some test data in my iPhone simulator’s address book to test out some functionality in the Raptr iPhone app, but adding contacts one by one would have been onerous, especially since I wanted several hundred!

Thankfully, you can programmatically add contacts to the iPhone contacts so I came up with the following snippet for a quick and dirty way to add a bunch of random contacts with random email addresses:

ABAddressBookRef addressBook = ABAddressBookCreate();

// create 200 random contacts
for (int i = 0; i < 200; i++)
{
	// create an ABRecordRef
	ABRecordRef record = ABPersonCreate();

	ABMutableMultiValueRef multi = ABMultiValueCreateMutable(kABStringPropertyType);

	NSString *email = [NSString stringWithFormat:@"%i@%ifoo.com", i, i];
	ABMultiValueAddValueAndLabel(multi, email, kABHomeLabel, NULL);

	NSString *fname = [NSString stringWithFormat:@"Name %i", i];
	NSString *lname = [NSString stringWithFormat:@"Last %i", i];

	// add the first name
	ABRecordSetValue(record, kABPersonFirstNameProperty, fname, NULL);

	// add the last name
	ABRecordSetValue(record, kABPersonLastNameProperty, lname, NULL);

	// add the home email
	ABRecordSetValue(record, kABPersonEmailProperty, multi, NULL);

	// add the record
	ABAddressBookAddRecord(addressBook, record, NULL);
}

// save the address book
ABAddressBookSave(addressBook, NULL);

// release
CFRelease(addressBook);

Put this inside -viewDidLoad or -loadView, launch the simulator and you’re set: 200 random contacts added to the simulator’s Contacts app. Make sure you remove this code snippet after you’ve run it once or you’ll keep adding random contacts. If you ever want to clear out the contacts on the simulator just go to the menu: iPhone Simulator -> Reset Content and Settings…

No related posts.