keys values in array like array[0] and so on - iphone

I am using this code
NSDictionary *yourDictionary;
NSArray * yourKeys;
yourKeys = [yourDictionary allValues];
to get the value of dictionary. But i want that array output in this form : array[0] ,array[1] while I am getting the output in console as below:-
2013-01-12 18:44:10.213 Birthday_Reminder[2871:c07] (
{
},
"Arpit Sihare")
and so on values.
so plz help me to get those values in this form and also I'm using KABPersonfirstnameproperty to retrieve those name from address book.
ABAddressBookRef addressBook = ABAddressBookCreate();
NSArray *thePeople = (NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);
NSMutableArray* allPeoplesDicts = [NSMutableArray array];
for (id person in thePeople)
{
ABMultiValueRef phone =(NSString*)ABRecordCopyValue(person, kABPersonPhoneProperty);
NSString* name = (NSString *)ABRecordCopyCompositeName(person);
// NSMutableArray* phones = [[NSMutableArray alloc] init];
NSDictionary *phones=[[NSDictionary alloc]init ];
for (CFIndex i = 0; i < ABMultiValueGetCount(phones); i++)
{
NSString *phone = [(NSString *)ABMultiValueCopyValueAtIndex(phones,i) autorelease];
[phones addObject:phone];
}
NSDictionary* personDict = [[NSDictionary alloc] initWithObjectsAndKeys:name,#"Name",phones,#"PhoneNumbers",nil];
[phones release];
NSArray * yourKeys;
yourKeys = [personDict allValues];
NSLog(#"%#",yourKeys);
[allPeoplesDicts addObject:personDict];
[personDict release];
}
and I want firstname in array form that when i use nslog(#"%#",array[0]) it should print value stored in array first place and soon like array[1]....

It's too hard to understand what you are trying to say. I tried and found...
If you just want to store all the firstName (which is your key I think) then just make yourKeys an NSMutableArray and add the names to that Array. :
[yourKeys addObject:names];
Simple !!

Related

Ios NSDictionary array - grouping values and keys

I have the following result of NSDictionary of Array
Bath = {
Keynsham = (
"nsham companies"
);
};
Bath = {
"Midsomer Norton" = (
"Keynsham companies"
);
};
Bath = {
"Norton Radstock" = (
"Keynsham taxi companies"
);
};
Birmingham = {
"Acock's Green" = (
"Acock's Green taxi companies"
);
};
Birmingham = {
"Alcester Lane's End" = (
"Alcester Lane's End taxi companies"
);
};
How can i combine the values and keys so that I end up with only one category as shown below;
Bath = {
"Norton Radstock" = (
"Keynsham taxi companies"
);
"Midsomer Norton" = (
"Keynsham companies"
);
Keynsham = (
"nsham companies"
);
};
I am not sure if this is the best way to explain it
the code is as follows
//all Nssarrays allocated/ initialised
NSURL *url=[NSURL URLWithString:#"http://y.php"];
NSData *data= [NSData dataWithContentsOfURL:url];
NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:Nil];
//instantiate arrays to hold data
NSMutableDictionary *dictArray=[[NSMutableDictionary alloc]init];
NSArray *cityName=[[NSArray alloc]init];
NSArray *townName=[[NSArray alloc]init];
NSArray *taxis=[[NSArray alloc]init];
NSArray *ids=[[NSArray alloc]init];
for (int i=0; i<json.count; i++)
{
//cityName=[[NSMutableArray alloc] initWithCapacity:json.count];
ids = [[json objectAtIndex:i] objectForKey:#"id"];
cityName = [[json objectAtIndex:i] objectForKey:#"cityName"];
townName=[[json objectAtIndex:i] objectForKey:#"townName"];
taxis=[[json objectAtIndex:i] objectForKey:#"taxis"];
NSMutableArray *taxisArray=[[NSMutableArray alloc] initWithObjects:taxis,nil];
NSMutableDictionary *towensdict=[[ NSMutableDictionary alloc] initWithObjectsAndKeys:taxisArray,townName, nil];
NSMutableDictionary *cities1=[[NSMutableDictionary alloc] initWithObjectsAndKeys:towensdict,cityName, nil];
NSLOG (#"%#", cities1) here, gives me the print out above
[dictArray addEntriesFromDictionary:cities1 ];
Then I tried Jdodgers solution as follows;
NSMutableDictionary *combinedDictionary = [[NSMutableDictionary alloc] init];
for (NSDictionary *currentDictionary in dictArray) {
NSArray *keys = [currentDictionary allKeys];
for (int n=0;n<[keys count];n++) {
NSMutableDictionary *dictionaryToAdd = [combinedDictionary valueForKey:[keys objectAtIndex:n]];
if (!dictionaryToAdd) dictionaryToAdd = [[NSMutableDictionary alloc] init];
[dictionaryToAdd setValuesForKeysWithDictionary:[currentDictionary valueForKey:[keys objectAtIndex:n]]];
[combinedDictionary setValue:dictionaryToAdd forKey:[keys objectAtIndex:n]];
NSLog(#"%#", currentDictionary);
}
}
//this gives error "unrecognized selector sent to instance", here is the print out
combinedDictionary NSMutableDictionary * 0x000000010012e580
currentDictionary NSDictionary *const 0x0000000100116460
dictArray NSMutableDictionary * 0x000000010012e220
[0] key/value pair
key id 0x0000000100116460
[0] id
value id 0x000000010012e440
[0] id
keys NSArray * 0x0000000000000000
You could create an NSMutableDictionary and loop through your array, adding the keys to the mutable dictionary using the allKeys.
For example, if your array was called dictArray, you could do:
NSMutableDictionary *combinedDictionary = [[NSMutableDictionary alloc] init];
for (NSDictionary *currentDictionary in dictArray) {
NSArray *keys = [currentDictionary allKeys];
for (int n=0;n<[keys count];n++) {
NSMutableDictionary *dictionaryToAdd = [combinedDictionary valueForKey:[keys objectAtIndex:n]];
if (!dictionaryToAdd) dictionaryToAdd = [[NSMutableDictionary alloc] init];
[dictionaryToAdd setValuesForKeysWithDictionary:[currentDictionary valueForKey:[keys objectAtIndex:n]]];
[combinedDictionary setValue:dictionaryToAdd forKey:[keys objectAtIndex:n]];
}
}
This code first creates a dictionary combinedDictionary that will be your final dictionary. It loops through all of the dictionaries in your array and for each one does the following:
First, it gets an array of all keys in the dictionary. For the dictionaries you provided this array will look like #[#"Bath"] for the first 3 and #[#"Birmingam"] for the other two.
The code then loops through these keys and gets the already existing dictionary from the combined dictionary from this key. If the dictionary doesn't exist, one is created.
Then, it adds all of the values from the dictionary from the array and sets the new dictionary to be the one in combinedDictionary.

add data to NSMUtableArrray with keys by for loop

I'm new in iPhone, I want to add elements to NSMutableArray with each element's name
I created a MutableArray for keys , then other array for elements that I get them from object called Pages.
I wrote the following code
NSMutableArray *myArray;
NSMutableArray *arrayKey = [[NSMutableArray alloc] initWithObjects:#"b_pag_id", #"b_pag_bo_id", #"b_pag_num", #"b_pag_note", #"b_page_mark", #"b_page_stop", #"b_pag_user_id", nil];
for (int x=0; x<[pages count]; x++) {
Pages *myPages = (Pages *)[self.pages objectAtIndex:x];
NSString *b_pag_id2 = [NSString stringWithFormat:#"%d",myPages.b_pag_id];
NSString *b_pag_bo_id2 = [NSString stringWithFormat:#"%d",myPages.b_pag_bo_id];
NSString *b_pag_num2 = [NSString stringWithFormat:#"%d",myPages.b_pag_num];
NSString *b_pag_note2 = myPages.b_pag_note;
NSString *b_page_mark2 = [NSString stringWithFormat:#"%d",myPages.b_page_mark];
NSString *b_page_stop2 = [NSString stringWithFormat:#"%d",myPages.b_page_stop];
NSString *b_pag_user_id2 = [NSString stringWithFormat:#"%d",myPages.b_pag_user_id];
NSMutableArray *arrayValue = [[NSMutableArray alloc] initWithObjects:b_pag_id2, b_pag_bo_id2, b_pag_num2, b_pag_note2, b_page_mark2, b_page_stop2, b_pag_user_id2, nil];
NSDictionary *theReqDictionary = [NSDictionary dictionaryWithObjects:arrayValue forKeys:arrayKey];
myArray = [NSMutableArray arrayWithObjects:theReqDictionary,nil];
}
NSLog(#"array size: %d", [myArray count]);
I want to add every element to its key for example
element (b_pag_id2) its key (b_pag_id) ..etc
is this right ?? or how to do this ??
consider that NSLog(#"array size: %d", [myArray count]); gives me 1 and the size of my elements is 14
Before the loop you need to initialize the aray
NSMutableArray *myArray = [NSMutableArray array];
Inside the loop replace following:
myArray = [NSMutableArray arrayWithObjects:theReqDictionary,nil];
with
[myArray addObject:theReqDictionary];
The problem is that you are creating a new array with 1 dictionary in every loop iteration. Instead you need to initialize the array and add values one by one.
Each time through your loop you are creating a new array for myArray that has only one element. You should initialize an empty NSMutableArray before the loop and then simply add your new object to it instead of using arrayWithObjects: to create myArray..
Here i'm giving a short example, and i hope this will help you.
see this code :-
NSMutableArray *arrayValue = [[NSMutableArray alloc]initWithObjects:#"Value1",#"Value2",#"Value3", nil];
NSMutableArray *arrayKey = [[NSMutableArray alloc]initWithObjects:#"1",#"2",#"3", nil];
NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
for(int i=0;i<3;i++)
{
[dic setObject:[arrayValue objectAtIndex:i] forKey:[arrayKey objectAtIndex:i]];
}
//and you can see this by printing it using nslog-
NSLog(#"%#",[dic valueForKey:#"1"]);
Thank you!!!

Convert NSMutableArray to NSDictionary in order to use objectForKey?

I have an NSMutableArray that looks like this
{
"#active" = false;
"#name" = NAME1;
},
{
"#active" = false;
"#name" = NAME2;
}
Is there a way to convert this to an NSDictionary and then use objectForKey to get an array of the name objects? How else can I get these objects?
There is a even shorter form then this proposed by Hubert
NSArray *allNames = [array valueForKey:#"name"];
valueForKey: on NSArray returns a new array by sending valueForKey:givenKey to all it elements.
From the docs:
valueForKey:
Returns an array containing the results of invoking
valueForKey: using key on each of the array's objects.
- (id)valueForKey:(NSString *)key
Parameters
key The key to retrieve.
Return Value
The value of the retrieved key.
Discussion
The returned array contains NSNull elements for each object that returns nil.
Example:
NSArray *array = #[#{ #"active": #NO,#"name": #"Alice"},
#{ #"active": #NO,#"name": #"Bob"}];
NSLog(#"%#\n%#", array, [array valueForKey:#"name"]);
result:
(
{
active = 0;
name = Alice;
},
{
active = 0;
name = Bob;
}
)
(
Alice,
Bob
)
If you want to convert NSMutableArray to corresponding NSDictionary, just simply use mutableCopy
NSMutableArray *phone_list; //your Array
NSDictionary *dictionary = [[NSDictionary alloc] init];
dictionary = [phone_list mutableCopy];
This is an Array of Dictionary objects, so to get the values you would:
[[myArray objectAtIndex:0]valueForKey:#"name"]; //Replace index with the index you want and/or the key.
This is example one of the exmple get the emplyee list NSMutableArray and create NSMutableDictionary.......
NSMutableArray *emloyees = [[NSMutableArray alloc]initWithObjects:#"saman",#"Ruchira",#"Rukshan",#"ishan",#"Harsha",#"Ghihan",#"Lakmali",#"Dasuni", nil];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for (NSString *word in emloyees) {
NSString *firstLetter = [[word substringToIndex:1] uppercaseString];
letterList = [dict objectForKey:firstLetter];
if (!letterList) {
letterList = [NSMutableArray array];
[dict setObject:letterList forKey:firstLetter];
}
[letterList addObject:word];
} NSLog(#"dic %#",dict);
yes you can
see this example:
NSDictionary *responseDictionary = [[request responseString] JSONValue];
NSMutableArray *dict = [responseDictionary objectForKey:#"data"];
NSDictionary *entry = [dict objectAtIndex:0];
NSString *num = [entry objectForKey:#"num"];
NSString *name = [entry objectForKey:#"name"];
NSString *score = [entry objectForKey:#"score"];
im sorry if i can't elaborate much because i am also working on something
but i hope that can help you. :)
No, guys.... the problem is that you are stepping on the KeyValue Mechanism in cocoa.
KeyValueCoding specifies that the #count symbol can be used in a keyPath....
myArray.#count
SOOOOOO.... just switch to the ObjectForKey and your ok!
NSMutableDictionary *myDictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:#"theValue", #"#name", nil];
id kvoReturnedObject = [myDictionary valueForKey:#"#name"]; //WON'T WORK, the # symbol is special in the valueForKey
id dictionaryReturnedObject = [myDictionary objectForKey:#"#name"];
NSLog(#"object = %#", dictionaryReturnedObject);

How to get contacts detail of iphone and make CSV file of that contact

I want to get contact details in an iPhone with information like First Name, Last Name, Phone Number, Phone Number Type, Email Address, Email Address Type etc..
Can anyone help me with that?
I want to make a .csv file out of the contact details in a particular iPhone. I want to fetch iPhone address book data.
Following is the code to get all informations of iPhone contact book...
-(void)collectContacts
{
NSMutableDictionary *myAddressBook = [[NSMutableDictionary alloc] init];
ABAddressBookRef addressBook = ABAddressBookCreate();
CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(addressBook);
for(int i = 0;i<ABAddressBookGetPersonCount(addressBook);i++)
{
ABRecordRef ref = CFArrayGetValueAtIndex(people, i);
// Get First name, Last name, Prefix, Suffix, Job title
NSString *firstName = (NSString *)ABRecordCopyValue(ref,kABPersonFirstNameProperty);
NSString *lastName = (NSString *)ABRecordCopyValue(ref,kABPersonLastNameProperty);
NSString *prefix = (NSString *)ABRecordCopyValue(ref,kABPersonPrefixProperty);
NSString *suffix = (NSString *)ABRecordCopyValue(ref,kABPersonSuffixProperty);
NSString *jobTitle = (NSString *)ABRecordCopyValue(ref,kABPersonJobTitleProperty);
[myAddressBook setObject:firstName forKey:#"firstName"];
[myAddressBook setObject:lastName forKey:#"lastName"];
[myAddressBook setObject:prefix forKey:#"prefix"];
[myAddressBook setObject:suffix forKey:#"suffix"];
[myAddressBook setObject:jobTitle forKey:#"jobTitle"];
NSMutableArray *arPhone = [[NSMutableArray alloc] init];
ABMultiValueRef phones = ABRecordCopyValue(ref, kABPersonPhoneProperty);
for(CFIndex j = 0; j < ABMultiValueGetCount(phones); j++)
{
CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(phones, j);
NSString *phoneLabel =(NSString*) ABAddressBookCopyLocalizedLabel (ABMultiValueCopyLabelAtIndex(phones, j));
NSString *phoneNumber = (NSString *)phoneNumberRef;
NSMutableDictionary *temp = [[NSMutableDictionary alloc] init];
[temp setObject:phoneNumber forKey:#"phoneNumber"];
[temp setObject:phoneLabel forKey:#"phoneNumber"];
[arPhone addObject:temp];
[temp release];
}
[myAddressBook setObject:arPhone forKey:#"Phone"];
[arPhone release];
CFStringRef address;
CFStringRef label;
ABMutableMultiValueRef multi = ABRecordCopyValue(ref, kABPersonAddressProperty);
for (CFIndex i = 0; i < ABMultiValueGetCount(multi); i++)
{
label = ABMultiValueCopyLabelAtIndex(multi, i);
CFStringRef readableLabel = ABAddressBookCopyLocalizedLabel(label);
address = ABMultiValueCopyValueAtIndex(multi, i);
CFRelease(address);
CFRelease(label);
}
ABMultiValueRef emails = ABRecordCopyValue(ref, kABPersonEmailProperty);
NSMutableArray *arEmail = [[NSMutableArray alloc] init];
for(CFIndex idx = 0; idx < ABMultiValueGetCount(emails); idx++)
{
CFStringRef emailRef = ABMultiValueCopyValueAtIndex(emails, idx);
NSString *strLbl = (NSString*) ABAddressBookCopyLocalizedLabel (ABMultiValueCopyLabelAtIndex (emails, idx));
NSString *strEmail_old = (NSString*)emailRef;
NSMutableDictionary *temp = [[NSMutableDictionary alloc] init];
[temp setObject:strEmail_old forKey:#"strEmail_old"];
[temp setObject:strLbl forKey:#"strLbl"];
[arEmail addObject:temp];
[temp release];
}
[myAddressBook setObject:arEmail forKey:#"Email"];
[arEmail release];
}
[self createCSV:myAddressBook];
}
-(void) createCSV :(NSMutableDictionary*)arAddressData
{
NSMutableString *stringToWrite = [[NSMutableString alloc] init];
[stringToWrite appendString:[NSString stringWithFormat:#"%#,",[arAddressData valueForKey:#"firstName"]]];
[stringToWrite appendString:[NSString stringWithFormat:#"%#,",[arAddressData valueForKey:#"lastName"]]];
[stringToWrite appendString:[NSString stringWithFormat:#"%#,",[arAddressData valueForKey:#"jobTitle"]]];
//[stringToWrite appendString:#"fname, lname, title, company, phonetype1, value1,phonetype2,value,phonetype3,value3phonetype4,value4,phonetype5,value5,phonetype6,value6,phonetype7,value7,phonetype8,value8,phonetype9,value9,phonetype10,value10,email1type,email1value,email2type,email2value,email3type,email3‌​value,email4type,email4value,email5type,email5value,website1,webs‌​ite2,website3"];
NSMutableArray *arPhone = (NSMutableArray*) [arAddressData valueForKey:#"Phone"];
for(int i = 0 ;i<[arPhone count];i++)
{
NSMutableDictionary *temp = (NSMutableDictionary*) [arPhone objectAtIndex:i];
[stringToWrite appendString:[NSString stringWithFormat:#"%#,",[temp valueForKey:#"phoneNumber"]]];
[stringToWrite appendString:[NSString stringWithFormat:#"%#,",[temp valueForKey:#"phoneNumber"]]];
[temp release];
}
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *documentDirectory=[paths objectAtIndex:0];
NSString *strBackupFileLocation = [NSString stringWithFormat:#"%#/%#", documentDirectory,#"ContactList.csv"];
[stringToWrite writeToFile:strBackupFileLocation atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
I used iApple's code above as a starting point and created a working version from it - this one just collects all address book entries in an array. As mentioned above the original iApple doesn't work, there's a few bugs in it. This one works, and was tested.
Note: This doesn't return any contacts that don't have a name set - you can remove that for your own code, I just did it because I only need contacts with names set, and NSMutableDictionary doesn't like nil entries (crashes).
In my own address book I have a few entries that are just an email - I am not sure how they got there, but it's certainly possible to have address book entries without a name. Keep that in mind when iterating over an address book.
I am using the full name as per Apple's recommendations - ABRecordCopyCompositeName returns a composite of first and last name in the order specified by the user.
Finally, I made this a static method and put it in a helper class.
This is for use with ARC!
// returns an array of dictionaries
// each dictionary has values: fullName, phoneNumbers, emails
// fullName is a string
// phoneNumbers is an array of strings
// emails is an array of strings
+ (NSArray *)collectAddressBookContacts {
NSMutableArray *allContacts = [[NSMutableArray alloc] init];
ABAddressBookRef addressBook = ABAddressBookCreate();
CFArrayRef people = ABAddressBookCopyArrayOfAllPeople(addressBook);
for(int i = 0;i<ABAddressBookGetPersonCount(addressBook);i++)
{
NSMutableDictionary *aPersonDict = [[NSMutableDictionary alloc] init];
ABRecordRef ref = CFArrayGetValueAtIndex(people, i);
NSString *fullName = (__bridge NSString *) ABRecordCopyCompositeName(ref);
if (fullName) {
[aPersonDict setObject:fullName forKey:#"fullName"];
// collect phone numbers
NSMutableArray *phoneNumbers = [[NSMutableArray alloc] init];
ABMultiValueRef phones = ABRecordCopyValue(ref, kABPersonPhoneProperty);
for(CFIndex j = 0; j < ABMultiValueGetCount(phones); j++) {
NSString *phoneNumber = (__bridge NSString *) ABMultiValueCopyValueAtIndex(phones, j);
[phoneNumbers addObject:phoneNumber];
}
[aPersonDict setObject:phoneNumbers forKey:#"phoneNumbers"];
// collect emails - key "emails" will contain an array of email addresses
ABMultiValueRef emails = ABRecordCopyValue(ref, kABPersonEmailProperty);
NSMutableArray *emailAddresses = [[NSMutableArray alloc] init];
for(CFIndex idx = 0; idx < ABMultiValueGetCount(emails); idx++) {
NSString *email = (__bridge NSString *)ABMultiValueCopyValueAtIndex(emails, idx);
[emailAddresses addObject:email];
}
[aPersonDict setObject:emailAddresses forKey:#"emails"];
// if you want to collect any other info that's stored in the address book, it follows the same pattern.
// you just need the right kABPerson.... property.
[allContacts addObject:aPersonDict];
} else {
// Note: I have a few entries in my phone that don't have a name set
// Example one could have just an email address in their address book.
}
}
return allContacts;
}
First you will need to use the address book framework so this must be added to your Xcode project.
Next you will need to break the task down into a couple steps.
1) Get the people inside the address book
2) Create your .csv file. I'm assuming you know something about CSV file formatting using characters to separate fields and when to add return characters so you have a properly formatted file. This is probably left for another question thread if you need help with this.
3) Save your .csv file somewhere
1) To get an array of all people in the address book you would do something like the following. The reference documentation for ABAddressBook is here. It should be very helpful in helping you access the data.
ABAddressBook *sharedBook = [ABAddressBook sharedAddressBook];
NSArray *peopleList = [sharedBook people];
2) You will have to iterate through each of the people and build your overall csv data. Usually you would manually create the csv data in an NSString and then convert it to NSData and save the NSData to a file. This is not ideal if you are dealing with a really large set of data. If this is the case then you would probably want some code to write your csv data to the file in chunks so you can free memory as you go. For simplicity sake my code just shows you creating the full file then saving the whole works.
NSString *csvString = #"";
for(ABPerson *aPerson in peopleList) {
//Do something here to write each property you want to the CSV file.
csvString = [csvString stringByAppendingFormat:#"'%#',"
[aPerson valueForProperty:kABFirstNameProperty]];
}
NSData *csvData = [csvString dataUsingEncoding:NSUTF8StringEncoding];
3) Write you file to somewhere
//This is an example of writing your csv data to a file that will be saved in the application's sand box directory.
//This file could be extracted using iTunes file sharing.
//Get the proper path to save the file
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:#"my_file.csv"];
//Actually write the data
BOOL isSuccessful = [csvData writeToFile:fullPath atomically:NO];
if(isSuccessful) {
//Do something if the file was written
} else {
//Do something if there was an error writing the file
}
See Adress Book API particulary Importing and Exporting Person and Group Records
chack also the Address Book Test example in this blog

ABAddressBook store values in NSDictionary

I have an app that displays ABAddressBook contacts in a UITableView. Currently I'm reading the contacts into an NSDictionary, however this appears to crash for some users, which I suspect is a memory issue.
Is there another approach to display ABAddressBook contacts in a UITableView without either first storing them in an NSDictionary or using ABPeoplePicker?
A different way using ARC:
ABAddressBookRef addressBook = ABAddressBookCreate();
CFArrayRef addressBookData = ABAddressBookCopyArrayOfAllPeople(addressBook);
CFIndex count = CFArrayGetCount(addressBookData);
NSMutableArray *contactsArray = [NSMutableArray new];
for (CFIndex idx = 0; idx < count; idx++) {
ABRecordRef person = CFArrayGetValueAtIndex(addressBookData, idx);
NSString *firstName = (__bridge_transfer NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
if (firstName) {
NSDictionary *dict = [NSDictionary dictionaryWithObject:firstName ForKey:#"name"];
[contactsArray addObject:dict];
}
}
CFRelease(addressBook);
CFRelease(addressBookData);
You can use following way,
ABAddressBookRef ab = ABAddressBookCreateWithOptions(NULL, NULL);
NSArray *arrTemp = (NSArray *)ABAddressBookCopyArrayOfAllPeople(ab);
The above 2 lines will create an array for all your contacts on the iPhone.
Now whatever property of a contact you want to display you can display by using the below code. For example, I want to display the first name of all contacts and then create one Mutable array called it arrContact.
NSMutableArray *arrContact = [[NSMutableArray alloc] init];
for (int i = 0; i < [arrTemp count]; i++)
{
NSMutableDictionary *dicContact = [[NSMutableDictionary alloc] init];
NSString *str = (NSString *) ABRecordCopyValue([arrTemp objectAtIndex:i], kABPersonFirstNameProperty);
#try
{
[dicContact setObject:str forKey:#"name"];
}
#catch (NSException * e) {
[dicContact release];
continue;
}
[arrContact addObject:dicContact];
[dicContact release];
}
Now just display it using the arrContact array in a table view..
Same as Abizern's answer, but if you want to display full names that are localized, use ABRecordCopyCompositeName. (In English names are "First Last", but in Chinese names are "LastFirst").
ABRecordRef person = CFArrayGetValueAtIndex(addressBookData, idx);
NSString *fullName = (__bridge_transfer NSString *)ABRecordCopyCompositeName(person);//important for localization