This question already has answers here:
How would I combine two arrays in Objective-C?
(2 answers)
Closed 9 years ago.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *error;
json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(#"json.... %#",json);
id jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:nil];
NSLog(#"jsonObject=%#", jsonObject);
NSDictionary *checkArray=[json valueForKey:#"ND"];
NSArray *tel = [checkArray valueForKey:#"FN"];
testArray = [[NSMutableArray alloc]init];
testArray1 = [[NSMutableArray alloc]init];
newsarray = [[NSMutableArray alloc]init];
for (id photo in tel)
{
if (photo == [NSNull null])
{
NSString *test8;
test8 = #"empty";
[testArray addObject:test8];
}
else
{
// photo isn't null. It's an array
NSArray *innerPhotos = photo;
[testArray addObject:photo];
}
}
NSArray *tel1 = [checkArray valueForKey:#"LN"];
for (id photo1 in tel1)
{
if (photo1 == [NSNull null])
{
NSString *test8;
test8 = #"empty";
[testArray1 addObject:test8];
}
else
{
// photo isn't null. It's an array
//NSArray *innerPhotos1 = photo1;
[testArray1 addObject:photo1];
}
}
newsarray = [NSMutableArray arrayWithArray:[testArray arrayByAddingObjectsFromArray:testArray1]];
NSLog(#"testArray =%#",newsarray);
here i want to combine two array values "testArray" and "testArray1"
my mutablearray values are
testArray = aa, bb, cc, dd...
testArray1= xx, yy, zz, ss...
i would like to expect my output like
aa xx, bb yy, cc zz, dd ss
Try this:
for (int i=0;i<[testArray count];i++){
NSString *tmpObject=[NSString stringWithFormat:#"%# %#",
[testArray objectAtIndex:i],
[testArray1 objectAtIndex:i]];
[newArray addObject tmpObject];
tmpObject=nil;
}
you can do something like below..
NSMutableArray *aryFinal=[[NSMutableArray alloc]init];
int count = [testArray count]+[testArray1 count];
for(int i=0;i<count;i++)
{
if(i%2==0)
[aryFinal addobject:[testArray objectAtIndex:i]];
else
[aryFinal addobject:[testArray1 objectAtIndex:i]];
}
let me know it is working or not!!!
NSMutableArray *array1 = [NSMutableArray arrayWithObjects:#"AA",#"BB",#"CC" nil];
NSArray *array2 = [NSArray arrayWithObjects:#"XX",#"YY",#"ZZ" nil];
for (int i=0; i<[array1 count];i++)
[array1 replaceObjectAtIndex:i
withObject:[NSString stringWithFormat:#"%# %#",
array1[i],
array2[i]]];
NSLog(#"%#",array1);
Output:
"AA XX","BB YY","CC ZZ"
To simply add two arrays:
[testArray setArray: testArray1];
But if you want desired result:
NSMutableArray *arrFinal=[[NSMutableArray alloc]init];
for(int i = 0; i < (testArray.count + testArray1.count); i++)
{
if(i%2 == 0)
[arrFinal addobject:[testArray objectAtIndex:i]];
else
[arrFinal addobject:[testArray1 objectAtIndex:i]];
}
Do not need to go for third array. You can use replaceObjectAtIndex method of NSMutableArray.
This way..
NSMutableArray *array1 = [NSMutableArray arrayWithObjects:#"aa",#"bb", nil];
NSArray *array2 = [NSArray arrayWithObjects:#"xx",#"yy", nil];
for (int i=0; i<[array1 count];i++)
[array1 replaceObjectAtIndex:i withObject:[NSString stringWithFormat:#"%# %#",array1[i],array2[i]]];
for aa xx, bb yy, cc zz, dd ss output:
int i=-1;
for(int k =0;k<[testArray1 count];++k)
{
i=i+2;
[testArray insertObject:[testArray1 objectAtIndex:k] atIndex:i];
}
NSMutableArray *array1,*array2;
//////array1 and array2 initialise it with your values
NSMutableArray *finalArray = [[NSMutableArray alloc]init]
int totalcount = 0;
if (array1.count > array2.count) {
totalcount = array1.count;
}
else
totalcount = array2.count;
for (int i = 0; i<totalcount; i++) {
if (i <= array1.count-1) {
[finalArray addObject:[array1 objectAtIndex:i]];
}
if (i <= array2.count-1) {
[finalArray addObject:[array2 objectAtIndex:i]];
}
}
Related
This is a function that I use to fetch the contact name and email from the addressbook.
-(void) fetchFriendsAllDetails {
NSMutableArray *allEmails = [[NSMutableArray alloc] initWithCapacity:_peopleList.count];
for (int i = 0; i < _peopleList.count; i++) {
ABRecordRef person = (__bridge ABRecordRef)([_peopleList objectAtIndex:i]);
ABMultiValueRef emails = ABRecordCopyValue(person, kABPersonEmailProperty);
NSString *name=[[NSString stringWithFormat:#"%#",(__bridge_transfer NSString *)ABRecordCopyCompositeName(person)] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSLog(#"id:%d,name:%#",i,name);
for (int j=0; j < ABMultiValueGetCount(emails); j++) {
NSString* email = (__bridge NSString*)ABMultiValueCopyValueAtIndex(emails, j);
[allEmails addObject:email];
NSLog(#"id:%d,email:%#",i,email);
}
}
}
The output of the above is as follows:
id:0,name:John Appleseed
id:0,email:John-Appleseed#mac.com
id:1,name:Kate Bell
id:1,email:kate-bell#mac.com
id:1,email:www.icloud.com
id:2,name:Anna Haro
id:2,email:anna-haro#mac.com
id:3,name:Daniel Higgins Jr.
id:3,email:d-higgins#mac.com
id:4,name:David Taylor
id:5,name:Hank M. Zakroff
id:5,email:hank-zakroff#mac.com
I want to make a dictionary in the above function that will contain the output in the following format
{
id:0
name:John Appleseed
email:John-Appleseed#mac.com
selectedFlag:NO
},
{
id:1
name:Kate Bell
email:kate-bell#mac.com, www.icloud.com
selectedFlag:NO
},
{
id:2
name:Anna Haro
email:John-Appleseed#mac.com
selectedFlag:NO
},
{
id:3
name:Daniel Higgins Jr.
email:d-higgins#mac.com
selectedFlag:NO
},
{
id:4
name:David Taylor
email:""
selectedFlag:NO
},
id:5
nameHank M. Zakroff
email:hank-zakroff#mac.com
selectedFlag:NO
}
I have basic understanding about NSMutableDictionary, but dont know in through detail to implement this. Can you help me create it?
Use NSMutableDictionary's setObject:forKey: method.
- (void)setObject:(id)anObject forKey:(id < NSCopying >)aKey
From official documentation, this method:
Adds a given key-value pair to the dictionary.
For example, we can modify your code to create the required array of dictionaries. We create an NSMutabeDictionary object for every index of for-loop and keep adding it in an
NSMutableArray object.
-(void) fetchFriendsAllDetails
{
// allocate array
NSMutableArray *array = [[NSMutableArray alloc]init];
NSMutableArray *allEmails = [[NSMutableArray alloc] initWithCapacity:_peopleList.count];
NSMutableDictionary *dictionary;
for (int i = 0; i < _peopleList.count; i++)
{
dictionary = [[NSMutableDictionary alloc]init];
ABRecordRef person = (__bridge ABRecordRef)([_peopleList objectAtIndex:i]);
ABMultiValueRef emails = ABRecordCopyValue(person, kABPersonEmailProperty);
NSString *name=[[NSString stringWithFormat:#"%#",(__bridge_transfer NSString *)ABRecordCopyCompositeName(person)] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
// create key -vale pair for id and name
[dictionary setObject:[NSNumber numberWithInt:i] forKey:#"id"]; // here we used int wrapped inside and //object because NSMutable Dictionary expects an object instead of scalar type int.
[dictionary setObject:name forKey:#"name"];
NSLog(#"id:%d,name:%#",i,name);
// Create an NSMutableString to hold more than one email
NSMutableString *mutableEmail = [[NSMutableString alloc]init];
for (int j=0; j < ABMultiValueGetCount(emails); j++)
{
NSString* email = (__bridge NSString*)ABMultiValueCopyValueAtIndex(emails, j);
[mutableEmail appendString:email];
// append comma to separate more than one mail
if(j != ABMultiValueGetCount(emails) - 1)
{
[mutableEmail appendString:#","];
}
[allEmails addObject:email];
NSLog(#"id:%d,email:%#",i,email);
}
[dictionary setObject:mutableEmail forKey:#"email"];
// for boolean also. wrap inside an object
[dictionary setObject:[NSNumber numberWithBool:NO] forKey:#"id"];
// add dictionary to array
[array addObject:dictionary];
}
}
PS: I am writing this in Windows so please pardon me for any typos.
Did for your first part. Please try :-
NSDictionary *countriesListedByLetter = #{#"id" : #"0", #"name" : #"John Appleseed", #"email" : #"John-Appleseed#mac.com", #"selectedFlag": #"NO"};
NSLog(#"%#",countriesListedByLetter);
OUtPUt:--
{
email = "John-Appleseed#mac.com";
id = 0;
name = "John Appleseed";
selectedFlag = NO;
}
It looks like you want an array of dictionaries.
-(void) fetchFriendsAllDetails
{
NSMutableArray *allContacts = [[NSMutableArray alloc] initWithCapacity:_peopleList.count];
for (NSUInteger i = 0; i < _peopleList.count; i++)
{
ABRecordRef person = (__bridge ABRecordRef)([_peopleList objectAtIndex:i]);
ABMultiValueRef emails = ABRecordCopyValue(person, kABPersonEmailProperty);
NSString *name=[[NSString stringWithFormat:#"%#",(__bridge_transfer NSString *)ABRecordCopyCompositeName(person)] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSLog(#"id:%d,name:%#",i,name);
NSUInteger count = ABMultiValueGetCount(emails);
NSMutableArray *emailsM = [[NSMutableArray alloc] initWithCapacity:count];
for (NSUInteger j=0; j < ABMultiValueGetCount(emails); j++)
{
NSString* email = (__bridge NSString*)ABMultiValueCopyValueAtIndex(emails, j);
[emailsM addObject:email];
// NSLog(#"id:%d,email:%#",i,email);
}
[allContacts addObject:#{#"id": #(i),
#"name": name,
#"email": [NSArray arrayWithArray:emailsM],
#"selectedFlag": #(NO)}];
}
}
Try look in to the array of dictionaries.
NSMutableArray *allEmails = [[NSMutableArray alloc] initWithCapacity:_peopleList.count];
for (int i = 0; i < _peopleList.count; i++)
{
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init] ;
ABRecordRef person = (__bridge ABRecordRef)([_peopleList objectAtIndex:i]);
ABMultiValueRef emails = ABRecordCopyValue(person, kABPersonEmailProperty);
NSString *name=[[NSString stringWithFormat:#"%#",(__bridge_transfer NSString *)ABRecordCopyCompositeName(person)] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSLog(#"id:%d,name:%#",i,name);
[dict setObject:[NSNumber numberWithInt:i] forKey:#"id"];
[dict setObject:[NSNumber numberWithBool:false] forKey:#"seletedFlag"];
[dict setObject:name forKey:#"name"];
for (int j=0; j < ABMultiValueGetCount(emails); j++)
{
NSString* email = (__bridge NSString*)ABMultiValueCopyValueAtIndex(emails, j);
[dict setObject:email forKey:#"email"];
NSLog(#"id:%d,email:%#",i,email);
}
[allEmails addObject:dict];
[dict release];
}
}
NSLog(#"%#",allEmails);
Try this:
-(void) fetchFriendsAllDetails
{
NSMutableArray *allEmails = [[NSMutableArray alloc] initWithCapacity:_peopleList.count];
for (int i = 0; i < _peopleList.count; i++)
{
NSMutableDictionary *addressesDict = [[NSMutableDictionary alloc] initWithCapacity:4];
ABRecordRef person = (__bridge ABRecordRef)([_peopleList objectAtIndex:i]);
ABMultiValueRef emails = ABRecordCopyValue(person, kABPersonEmailProperty);
NSString *name=[[NSString stringWithFormat:#"%#",(__bridge_transfer NSString *)ABRecordCopyCompositeName(person)] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSLog(#"id:%d,name:%#",i,name);
[addressesDict setValue:[NSString stringWithFormat:#"%i",i] forKey:#"id"];
[addressesDict setValue:name forKey:#"name"];
for (int j=0; j < ABMultiValueGetCount(emails); j++)
{
NSMutableString *emailString = [[NSMutableString alloc]init];
NSString* email = (__bridge NSString*)ABMultiValueCopyValueAtIndex(emails, j);
[emailString appendString:email];
if(j != ABMultiValueGetCount(emails) - 1)
{
[emailString appendString:#","];
}
[allEmails addObject:emailString];
[emailString release];
}
[addressesDict setValue:#"NO" forKey:#"selectedFlag"];
[allEmails addObject:addressesDict];
}
NSLog(#"RESULT: %#",allEmails);
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Reverse NSString text
i am new on objectovec. i have a array having strings. how to reverse each string?
which method of NSArray and NSstring will help me out?
i want reversed string in the array.
thanks
Create a method that will return a reversed string.
-(NSString *)reverseString:(NSString *)string{
NSString *reverseString=[NSString new];
for (NSInteger i=string.length-1; i>-1; i--) {
reverseString=[reverseString stringByAppendingFormat:#"%c",[string characterAtIndex:i]];
}
return reverseString;
}
In your any of the method :
NSMutableArray *names=[NSMutableArray arrayWithObjects:#"anoop",#"johnson",#"wasim",nil];
for (NSInteger i=0; i<names.count; i++) {
names[i]=[self reverseString:names[i]];
}
NSLog(#"%#",names);
Hope this help
NSString *str=textEntered.text;//
NSMutableArray *temp=[[NSMutableArray alloc] init];
for(int i=0;i<[str length];i++)
{
[temp addObject:[NSString stringWithFormat:#"%c",[str characterAtIndex:i]]];
}
temp = [NSMutableArray arrayWithArray:[[temp reverseObjectEnumerator] allObjects]];
NSString *reverseString=#"";
for(int i=0;i<[temp count];i++)
{
reverseString=[NSString stringWithFormat:#"%#%#",reverseString,[temp objectAtIndex:i]];
}
NSLog(#"%#",reverseString);
NSString *str=textEntered.text;//
NSMutableArray *temp=[[NSMutableArray alloc] init];
for(int i=0;i<[str length];i++)
{
[temp addObject:[NSString stringWithFormat:#"%c",[str characterAtIndex:i]]];
}
temp = [NSMutableArray arrayWithArray:[[temp reverseObjectEnumerator] allObjects]];
NSString *reverseString=#"";
for(int i=0;i<[temp count];i++)
{
reverseString=[NSString stringWithFormat:#"%#%#",reverseString,[temp objectAtIndex:i]];
}
NSLog(#"%#",reverseString);
AnOther way for revers string NSStringEnumerationOptions
- (NSString *)reverseString:(NSString *)string {
NSMutableString *reversedString = [[NSMutableString alloc] init];
NSRange fullRange = [string rangeOfString:string];
NSStringEnumerationOptions enumerationOptions = (NSStringEnumerationReverse | NSStringEnumerationByComposedCharacterSequences);
[string enumerateSubstringsInRange:fullRange options:enumerationOptions usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
[reversedString appendString:substring];
}];
return reversedString;
}
Use
unichar c[yourstring.Length];
NSRange raneg={0,yourstring.Length};
[yourstring getCharacters:c range:raneg];
//c will be an array of your string do what ever you wish
Use this one to reverse your string and then store back to your array at same index.
-(NSString*)reverseString:(NSString*)string {
NSMutableString *reversedString;
int length = [string length];
reversedString = [NSMutableString stringWithCapacity:length];
while (length--) {
[reversedString appendFormat:#"%c", [string characterAtIndex:length]];
}
return reversedString;
}
But if you have mutable string then you can create a category
#interface NSMutableString (Reverse)
- (void)reverseString;
#end
#implementation NSMutableString (Reverse)
- (void)reverseString {
for (int i = 0; i < self.length/2; i++) {
int l = self.length - 1 - i;
NSRange iRange = NSMakeRange(i, 1);
NSRange lRange = NSMakeRange(l, 1);
NSString *iStr = [self substringWithRange:iRange];
NSString *lStr = [self substringWithRange:lRange];
[self replaceCharactersInRange:iRange withString:lStr];
[self replaceCharactersInRange:lRange withString:iStr];
}
}
#end
And then you can use this category method like this
NSArray *arr = [NSArray arrayWithObjects:[#"hello" mutableCopy], [#"Do it now" mutableCopy], [#"Test string, 123 123" mutableCopy], nil];
NSLog(#"%#",arr);
[arr makeObjectsPerformSelector:#selector(reverseString)];
NSLog(#"%#",arr);
I have Plist with list with List of Dictionaries(item0,item1,item2)..
generally when I display in screen ..it populates in ascending order...item0 then item1 then item2......and so on..I want the Plist to be display in reverse order as itemn,itemn-1.........item2,item1,item0
.
and this is how code goes...and How Can I reverse it ..need changes in Array below
NSMutableArray *Array=[NSMutableArray arrayWithArray:[self readFromPlist]];
NSMutableArray *items = [[NSMutableArray alloc] init];
for (int i = 0; i< [Array count]; i++)
//how to reverse by making changes here
//for (int i =[Array count] ; i>0; i--) does not work
{
id object = [Array objectAtIndex:i];
if ([object isKindOfClass:[NSDictionary class]])
{
NSDictionary *objDict = (NSDictionary *)object;
tempItemi =[[ECGraphItem alloc]init];
NSString *str=[objDict objectForKey:#"title"];
NSLog(#"str value%#",str);
float f=[str floatValue];
//my code here
}
Use reverse enumeration
for (id someObject in [myArray reverseObjectEnumerator]){
// print some info
NSLog([someObject description]);
}
For your code:
for (id object in [Array reverseObjectEnumerator]){
if ([object isKindOfClass:[NSDictionary class]])
{
NSDictionary *objDict = (NSDictionary *)object;
tempItemi =[[ECGraphItem alloc]init];
NSString *str=[objDict objectForKey:#"title"];
NSLog(#"str value%#",str);
float f=[str floatValue];
//my code here
}
}
Also in your code:
//for (int i =[Array count] ; i>0; i--) does not work
should be as
for (int i =[Array count]-1 ; i>=0; i--)
You are itrating from count to 1 whereas array has objects from index count-1 to 0
e.g.
Array with 10 objects has objects from index 0 to 9
for (int i =[Array count]-1 ; i >= 0; i--)
{
id object = [Array objectAtIndex:i];
if ([object isKindOfClass:[NSDictionary class]])
{
NSDictionary *objDict = (NSDictionary *)object;
tempItemi =[[ECGraphItem alloc]init];
NSString *str=[objDict objectForKey:#"title"];
NSLog(#"str value%#",str);
float f=[str floatValue];
//my code here
}
I have three array..say array1,array2,array3. All these arrays contains dictionary.Now, I want to copy all the objects of these array into a single array and display in table view.
My problem is that how will I copy those three array into 1.
Say;
NSMutableArray *array1 = [NSMutableArray arrayWithObject:Dict1];
NSMutableArray *array2 = [NSMutableArray arrayWithObject:Dict2];
NSMutableArray *array3 = [NSMutableArray arrayWithObject:Dict3];
Now, I want to copy the contains of array1, array2, array3 into array4.How will I do this.
Use this
NSMutableArray *array4 = [[NSMutableArray alloc] init];
[array4 addObjectsFromArray:array1];
[array4 addObjectsFromArray:array2];
[array4 addObjectsFromArray:array3];
//Do something on array4
[array4 release];
NSMutableArray *allObjs = [[NSMutableArray alloc] initWithArray: array1];
[allObjs addObjectsFromArray: array2];
[allObjs addObjectsFromArray: array3];
NSMutableArray *array4 = [[NSMutableArray alloc] init];
for (int i = 0; i < [array1 count]; i++)
{
[array4 addObject:[array1 objectAtIndex:i]];
}
for (int i = 0; i < [array2 count]; i++)
{
[array4 addObject:[array2 objectAtIndex:i]];
}
for (int i = 0; i < [array3 count]; i++)
{
[array4 addObject:[array3 objectAtIndex:i]];
}
//use your array4
[array4 release];
NSMutableArray * array4 = [NSMutableArray arrayWithObjects:[array1 objectAtIndex:0], [array2 objectAtIndex:0], [array3 objectAtIndex:0]];
I have Problem related to array Sorting.
I have an NSMutable array say's A.Which has an class object b on its each index.
class b contain's multiple field Like int,string and nsdate.
I want to sort the A array on the basis of class b time(NSdate) ascendingly.
I follow the date sorting question on stackoverflow but that's only for date array.
Sort NSArray of date strings or objects
Kindly guide me.
Thank's in advance
Here you go just modify some part of code for your requirement
- (NSArray *)sortedWeightEntriesByWeightDate:(NSArray *)unsortedArray {
NSMutableArray *tempArray = [NSMutableArray array];
NSMutableArray *sortedArray = [NSMutableArray arrayWithCapacity:0];
#try {
for(int i = 0; i < [unsortedArray count];i++) {
NSDateFormatter *df = [[NSDateFormatter alloc]init];
MyDataModal *entry = [unsortedArray objectAtIndex:i];
[df setDateFormat:#"yyyy-MM-dd"];
NSDate *date = [df dateFromString:entry.weightDate];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
if(date) {
[dict setObject:entry forKey:#"entity"];
[dict setObject:date forKey:#"date"];
[tempArray addObject:dict];
}
[df release];
}
NSInteger counter = [tempArray count];
NSDate *compareDate;
NSInteger index;
for(int i = 0 ; i < counter; i++) {
index = i;
compareDate = [[tempArray objectAtIndex:i] valueForKey:#"date"];
NSDate *compareDateSecond;
for(int j = i+1 ; j < counter; j++) {
compareDateSecond=[[tempArray objectAtIndex:j] valueForKey:#"date"];
NSComparisonResult result = [compareDate compare:compareDateSecond];
if(result == NSOrderedDescending) {
compareDate = compareDateSecond;
index=j;
}
}
if(i!=index)
[tempArray exchangeObjectAtIndex:i withObjectAtIndex:index];
}
NSInteger counterIndex = [tempArray count];
for(int i = 0; i < counterIndex ; i++) {
[sortedArray addObject:[[tempArray objectAtIndex:i] valueForKey:#"entity"]];
}
}
#catch (NSException * e) {
NSLog(#"An exception occured while sorting weight entries by date");
}
#finally {
return [NSArray arrayWithArray:sortedArray];
}
}
How about:
NSArray *myArray = [NSArray arrayWithObjects:
[NSDictionary dictionaryWithObjectsAndKeys:[NSDate distantFuture], #"theDate", nil],
[NSDictionary dictionaryWithObjectsAndKeys:[NSDate distantPast], #"theDate", nil],
nil];
NSLog(#"Before sorting: %#", myArray);
NSSortDescriptor *dateSortDescriptor = [NSSortDescriptor sortDescriptorWithKey: #"theDate" ascending: YES];
NSArray *sortedArray = [myArray sortedArrayUsingDescriptors:[NSArray arrayWithObject: dateSortDescriptor]];
NSLog(#"After Sorting: %#", sortedArray);
This presumes that the date you want to sort for has a key (it is a property, essentially.)