NSArray的词典和副本

时间:2013-11-19 10:01:24

标签: ios objective-c nsmutablearray nsxmlparser

我有一个巨大的问题,我觉得我永远不会摆脱它。我从我的服务器获得了一个xml文件,解析得很好。但我在那个xml文件中有重复项。事情是我需要摆脱我的NSMutableArray中的重复项,以便知道我的NSMutable数组中有什么,并显示一个小菜单,其中有部分是可用的,而不是。但我无法将好东西复制到另一个数组中,因为NSMutableArray实际上是一个字典数组。而且我不知道如何管理它们,我在过去两天尝试了几个没有结果的事情,所以如果有人可以帮助我,我将非常感激。

这是我的整个代码(希望它不会灼伤你的眼睛: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"]

//这里是魔术发生的地方           - &GT; if(([self ifStringExists:currentType] == NO)){                      [故事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

我的.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

1 个答案:

答案 0 :(得分:2)

如果您的解析器委托回调中有代码[stories addObject:[item copy]];,请不要盲目添加新项目 - 检查它是否已存在:

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

然后你根本不会有重复。

您不需要复制item,因为每次启动新元素时都会创建一个新元素。此外,如果您没有将'duplicate'定义为与整个字典的完全匹配,那么您将需要编写自己的contains类型方法,该方法迭代数组并检查您感兴趣的每个字典的部分英寸