Question

i have a huge huge problem, i feel like i will never get rid of it. i got a xml file coming from my server, parsing it well. but i got duplicates in that xml file. The thing is i need to get rid of the duplicates in my NSMutableArray, in order to know what i have in my NSMutable array and display a little menu with wich section is avaible and wich is not. But i can't manage to copy only the good stuff into another array since the NSMutableArray is as a matter of fact a Array of dictionaries. And i don't know how to manage them, i tried sevral things the past two days with no results, so please if someone can help me it would very appreciated.

here is my entire code (hope it doesn't burn you eyes :3) :

#include <CommonCrypto/CommonDigest.h>
#include <CommonCrypto/CommonHMAC.h>
#import "SizingDataViewController.h"
#import "LCYDataBackedTableView.h"

@implementation SizingDataViewController


- (void)viewDidLoad {
     //Add the following line if you want the list to be editable
    self.title = @"Last choice";
}

-(BOOL)ifStringExists:(NSString *)stringSentToCheck{

    for (int i = 0; i < ([stories count]); i++) {

        NSLog(@"i = %i", i);

        NSMutableString *stringToCheck = (NSMutableString *)[[stories objectAtIndex: i] objectForKey: @"type"];
        if ([stringToCheck isEqualToString:stringSentToCheck] == YES) {
            NSLog(@"%@", @"okay its OKAY ");
                return YES;
            }
}
    return NO;
 }

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *MyIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];

    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault  reuseIdentifier:MyIdentifier] autorelease];

    CGRect frame = CGRectMake(0, 0, 160, 50);
    UILabel *lbl1 = [[UILabel alloc] initWithFrame:frame];
    lbl1.textAlignment = NSTextAlignmentRight;
    [lbl1 setFont:[UIFont fontWithName:@"Helvetica" size:12.0]];
    [lbl1 setTextColor:[UIColor grayColor]];
    int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
    lbl1.text = [[stories objectAtIndex: storyIndex] objectForKey: @"creation_date"];//Modifier pour changer le texte affiché
    [cell.contentView addSubview:lbl1];
    [lbl1 release];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
}


- (NSInteger)tableView:(UITableView *)tableView  numberOfRowsInSection:(NSInteger)section {
    return [stories count];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}



- (void)parseXMLFileAtURL:(NSString *)URL
{
    stories = [[NSMutableArray alloc] init];
    NSData *xmlData = [URL dataUsingEncoding:NSUTF8StringEncoding];
    rssParser = [[[NSXMLParser alloc] initWithData:xmlData]autorelease];

    [rssParser setDelegate:self];

    [rssParser setShouldProcessNamespaces:NO];
    [rssParser setShouldReportNamespacePrefixes:NO];
    [rssParser setShouldResolveExternalEntities:NO];

    [rssParser parse];

}

- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
    NSString * errorString = [NSString stringWithFormat:@"Unable to download story feed from web site (Error code %i )", [parseError code]];
    NSLog(@"error parsing XML: %@", errorString);

    UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:@"Error loading content" message:errorString delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [errorAlert show];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
    currentElement = [elementName copy];
    if ([elementName isEqualToString:@"data"]) {
        item = [[NSMutableDictionary alloc] init];
        currentData_id = [[NSMutableString alloc] init];
        currentSizing_id = [[NSMutableString alloc] init];
        currentName = [[NSMutableString alloc] init];
        currentSize = [[NSMutableString alloc] init];
        currentType = [[NSMutableString alloc]init];
    }

}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
    if ([elementName isEqualToString:@"data"]) {
        [item setObject:currentData_id forKey:@"data_id"];
        [item setObject:currentSizing_id forKey:@"sizing_id"];
        [item setObject:currentName forKey:@"name"];
        [item setObject:currentSize forKey:@"size"];
            [item setObject:currentType forKey:@"type"]

// here is where the magic happens --> if (([self ifStringExists:currentType] == NO)){ [stories addObject:[item copy]]; } } }

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
    NSLog(@"found characters in found characters: %@", string);

    if ([currentElement isEqualToString:@"data_id"]) {
        [currentData_id appendString:string];
    } else if ([currentElement isEqualToString:@"sizing_id"]) {
        [currentSizing_id appendString:string];
    } else if ([currentElement isEqualToString:@"name"]) {
        [currentName appendString:string];
    } else if ([currentElement isEqualToString:@"size"]) {
        [currentSize appendString:string];
    }else if ([currentElement isEqualToString:@"type"]) {
        [currentType appendString:string];
    }
}

- (void)parserDidEndDocument:(NSXMLParser *)parser {

    [activityIndicator stopAnimating];
    [activityIndicator removeFromSuperview];

    NSLog(@"all done!");
    NSLog(@"stories array has %d items", [stories count]);
    [newsTable reloadData];
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {

    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)dealloc {

    [currentElement release];
    [rssParser release];
    [stories release];
    [item release];
    [currentData_id release];
    [currentSize release];
    [currentSizing_id release];
    [currentName release];
    [currentType release];

    [super dealloc];
}
@end

my .h

#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import "LCYDataBackedTableView.h"

@interface SizingDataViewController : LCYDataBackedTableView {

    IBOutlet UITableView * newsTable;


    UIActivityIndicatorView * activityIndicator;

    CGSize cellSize;

    NSXMLParser * rssParser;

    NSMutableArray * stories;

    NSMutableArray * newStories;

    NSMutableArray *filteredStories;

    NSString *l_uri;

    NSString *myId;

    NSString *idName;

    BOOL *uploaded;

    BOOL isFiltered;

    NSIndexPath *indexPaath;

    NSMutableDictionary * item;

    NSString * currentElement;
    NSMutableString * currentData_id, * currentSizing_id, * currentType, * currentName, * currentSize;

    NSDictionary *data, *data1, *data2, *data3, *data4;


}

- (void)parseXMLFileAtURL:(NSString *)URL;
-(void)lastChance;
-(BOOL)ifStringExists:(NSString *)stringSentToCheck;
-(void)lastChance;

@end
Was it helpful?

Solution

Where you have the code [stories addObject:[item copy]]; in your parser delegate callback, don't just blindly add the new item - check if it exists already:

if (![stories containsObject:item]) {
    [stories addObject:item copy];
}

Then you won't have duplicates at all.

You don't strictly need to copy item because you're creating a new one each time you start a new element. Also, if you don't define 'duplicate' as a full match to the entire dictionary then you will need to write your own contains type method which iterates the array and check the parts of each dictionary that you're interested in.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top