user6631314 user6631314 - 1 year ago 116
iOS Question

IOS:Objective-C: How to combine elements of arrays

I have an array of people objects stored in Core Data and I would like to create a string made by combining two attributes of each, as in firstname and lastname.

NSArray *firstArr = [[Employees valueForKey:@"first"] allObjects];
NSArray *secondArr = [[Employees valueForKey:@"last"] allObjects];

I can create a string from one attribute such as "John,Jane" with

NSString *firststr = [firstarr componentsJoinedByString:@","];

Can anyone suggest how to make a string that has the first and last names separated by commas as in
John Doe, Jane Doe
? Imagine there is a method but I cannot find it.

Answer Source

You can do it like this

NSArray *firstArr = @[@"Rajat" , @"Rajat1", @"Raj"];
NSArray *secondArr = @[@"Test" , @"Test1", @"Test2"];
NSString * str = @"";
for (int i=0; i< (firstArr<secondArr ? firstArr.count:secondArr.count); i++) {
    str = [str stringByAppendingString:[NSString stringWithFormat:@"%@ %@,",firstArr[i],secondArr[i]]];
str = [str substringToIndex:[str length]-1];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download