Plist in reverse order - iphone

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
}

Related

how to combine two mutable arrays values in single mutable array? [duplicate]

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]];
}
}

Reverse strings in array objectivec [duplicate]

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);

UISearchBar - search a NSDictionary of Arrays of Objects

I'm trying to insert a search bar in a tableview, that is loaded with information from a NSDictionary of Arrays. Each Array holds and object. Each object has several properties, such as Name or Address.
I've implemented the methods of NSSearchBar, but the code corresponding to the search it self, that i have working on another project where the Arrays have strings only, is not working, and I can't get to thr problem.
Here's the code:
'indiceLateral' is a Array with the alphabet;
'partners' is a NSDictionary;
'RLPartnersClass' is my class of Partners, each one with the properties (name, address, ...).
-(void)handleSearchForTerm:(NSString *)searchTerm {
NSMutableArray *sectionsToRemove = [[NSMutableArray alloc] init];
[self resetSearch];
for (NSString *key in self.indiceLateral) {
NSMutableArray *array = [partners valueForKey:key];
NSMutableArray *toRemove = [[NSMutableArray alloc] init];
for (NSString *name in array) {
if ([name rangeOfString:searchTerm options:NSCaseInsensitiveSearch].location == NSNotFound)
[toRemove addObject:name];
}
if ([array count] == [toRemove count])
[sectionsToRemove addObject:key];
[array removeObjectsInArray:toRemove];
[toRemove release];
}
[self.indiceLateral removeObjectsInArray:sectionsToRemove];
[sectionsToRemove release];
[theTable reloadData];
}
Can anyone help me please?
Thanks,
Rui Lopes
I've done it.
Example:
-(void)handleSearchForTerm:(NSString *)searchTerm {
NSMutableDictionary *finalDict = [NSMutableDictionary new];
NSString *currentLetter = [[NSString alloc] init];
for (int i=0; i<[indiceLateral count]; i++) {
NSMutableArray *elementsToDict = [[[NSMutableArray alloc] init] autorelease];
currentLetter = [indiceLateral objectAtIndex:i];
NSArray *partnersForKey = [[NSArray alloc] initWithArray:[partnersCopy objectForKey:[indiceLateral objectAtIndex:i]]];
for (int j=0; j<[partnersForKey count]; j++) {
RLNames *partnerInKey = [partnersForKey objectAtIndex:j];
NSRange titleResultsRange = [partnerInKey.clientName rangeOfString:searchTerm options:NSDiacriticInsensitiveSearch | NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0){
NSLog(#"found: %#", partnerInKey.clienteCity
[elementsToDict addObject:partnerInKey];
}
}
[finalDict setValue:elementsToDict forKey:currentLetter];
}
NSMutableDictionary *finalResultDict = [finalDict mutableDeepCopy];
self.partners = finalResultDict;
[finalResultDict release];
[theTable reloadData];
}

Use objectForKey return wrong type of key

I'm reading a data from file that is an array of NSDictionary. With each NSDictionary include a key with name "EnglishName" and a value is type of NSString. I'm get value of a NSDictionary, create new ViewController with initialization function likes : initWithName:[(NSDictionary*)oneObjectInArray objectForKey:#"EnglishName"]; Then use NavigationController to push it.
The first time i push it-> no problem. Then press back then do it again(click to create new ViewController and push) an error appears with inform : [__NSArrayM rangeOfString:]: unrecognized selector sent to instance 0x63509a0'.
-I have checked by add a command NSLog(#"%#", [object getObjectForKey:#"EnglishName"])->error.
Then i tried to read data again in didShowView function(after back). It works without any error.
Here is the code to get data from file. Too long but maybe help to solve this problem`- (void) getListStoriesAvailable
{
[_header removeAllObjects];
SAFE_RELEASE(saveDataFromDataFile)
[storiesAvailableArray removeAllObjects];
NSString * digit = #"0123456789";
NSString * ALPHA = #"ABCDEFGHIJKLMNOPQRSTUVWXYZ ";
for (int i = 0; i < 27; i++)
{
NSMutableArray * element = [[NSMutableArray alloc] init];
[storiesAvailableArray addObject:element];
[element release];
}
NSString * path = [NSString stringWithFormat: #"%#/data.ini",documentDirectory];
if ([[NSFileManager defaultManager] fileExistsAtPath:path])
{
saveDataFromDataFile = [[NSMutableArray alloc] initWithContentsOfFile:path];
for (int i = 0; i < [saveDataFromDataFile count]; i++)
[[saveDataFromDataFile objectAtIndex:i] setObject:#"NO" forKey:#"Downloading"];
for (int i = 0; i < [saveDataFromDataFile count]; i++)
{
NSDictionary * theStory = [saveDataFromDataFile objectAtIndex:i];
NSString * word = [theStory objectForKey:#"EnglishName"];
if ([word length] == 0) continue;
NSString * firstCharacter = [[word substringToIndex: 1] uppercaseString];
NSRange range;
//The special case when the name of story start with a digit, add the story into "0-9" header and index
range = [digit rangeOfString:firstCharacter];
if (range.location != NSNotFound)
{
[[storiesAvailableArray objectAtIndex:0] addObject:theStory];
continue;
}
//Check the index of the first character
range = [ALPHA rangeOfString:firstCharacter];
if (range.location != NSNotFound)
{
[[storiesAvailableArray objectAtIndex:(range.location + 1)] addObject:theStory];
continue;
}
}
}
NSMutableArray * temp = [[NSMutableArray alloc] init];
for (int i = 0; i < [storiesAvailableArray count]; i++)
{
if ([[storiesAvailableArray objectAtIndex:i] count] != 0)
{
[_header addObject:[ALPHA_ARRAY objectAtIndex:i]];
[temp addObject:[storiesAvailableArray objectAtIndex:i]];
}
}
[storiesAvailableArray removeAllObjects];
for (int i = 0; i < [temp count]; i++)
[storiesAvailableArray addObject:[temp objectAtIndex:i]];
//storiesAvailableArray = temp;
[temp release];
}
`
And there is code to get NSDictionary
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
currentTable = tableView;
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSInteger row = [indexPath row];
NSDictionary * story;
if (tableView == listStoriesAvailable) story = [[storiesAvailableArray objectAtIndex:[indexPath section]] objectAtIndex:row];
_storyDetail = [[StoryViewController alloc] initWithName:[story objectForKey:#"EnglishName"]];
[self.navigationController setDelegate:self];
[self.navigationController pushViewController:_storyDetail animated:YES];
}
So what is problem ? Pls help!
You're not retaining your dictionary.
Please edit your question and add the code where your NSDictionary gets created.

how to remove duplicate value in NSMutableArray

i'm scanning wifi info using NSMutableArray, but there are few duplicate values appear, so i try to use following code but still getting the duplicate values,
if([scan_networks count] > 0)
{
NSArray *uniqueNetwork = [[NSMutableArray alloc] initWithArray:[[NSSet setWithArray:scan_networks] allObjects]];
[scan_networks removeAllObjects];
NSSortDescriptor *networkName = [[[NSSortDescriptor alloc] initWithKey:#"SSID_STR" ascending:YES] autorelease];
NSArray *descriptors = [NSArray arrayWithObjects:networkName,nil];
[scan_networks addObjectsFromArray:[uniqueNetwork sortedArrayUsingDescriptors:descriptors]];
}
how this can be resolve, thanks
You can use NSSET but if you it is only used when order doesn't matter if order matter then go for this approach.I have used it and it give perfect answer. in Place of NSmutableArray array put your NSmutableArray which contains duplicate Value.
NSArray *copy = [NSmutableArray copy];
NSInteger index = [copy count] - 1;
for (id object in [copy reverseObjectEnumerator])
{
if ([NSmutableArray indexOfObject:object inRange:NSMakeRange(0, index)] != NSNotFound)
{
[NSmutableArray removeObjectAtIndex:index];
}
index--;
}
[copy release];
You should be using an NSMutableSet in the first place.
For eliminating all double entries in an array, see this question:
Make NSMutableArray or NSMutableSet unique.
Here is the code of removing duplicates values from NSMutable Array..it will work for you.
myArray is your Mutable Array that you want to remove duplicates values..
for(int j = 0; j < [myArray count]; j++){
for( k = j+1;k < [myArray count];k++){
NSString *str1 = [myArray objectAtIndex:j];
NSString *str2 = [myArray objectAtIndex:k];
if([str1 isEqualToString:str2])
[myArray removeObjectAtIndex:k];
}
}
// Now print your array and
I think its better to do this:
NSMutableIndexSet *indexes = [[NSMutableIndexSet alloc]init];
for(int j = 0; j < [myArray count]; j++) {
for( k = j+1;k < [myArray count];k++) {
NSString *str1 = [myArray objectAtIndex:j];
NSString *str2 = [myArray objectAtIndex:k];
if([str1 isEqualToString:str2])
[indexes addIndex:k];
}
}
[myArray removeObjectsAtIndexes:indexes];
You can run into problems if you manipulate the array while looping in my experience.
This is another way:
- (NSArray *)removeDuplicatesFrom:(NSArray *)array {
NSSet *set = [NSSet setWithArray:array];
return [set allObjects];
}
maybe you can try the NSArray category.
#import <Foundation/Foundation.h>
#interface NSArray(filterRepeat)
-(NSArray *)filterRepeat;
#end
#import "NSArray+repeat.h"
#implementation NSArray(filterRepeat)
-(NSArray *)filterRepeat
{
NSMutableArray * resultArray =[NSMutableArray array];
[self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if (![resultArray containsObject: obj]) {
[resultArray addObject: obj];
}
}];
return resultArray;
}
#end