【问题标题】:NSArray of dictionaries and copy字典和副本的 NSArray
【发布时间】:2013-12-02 19:42:20
【问题描述】:

我有一个巨大的巨大问题,我觉得我永远无法摆脱它。我有一个来自我的服务器的 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"]

// 这里是魔法发生的地方 --> if (([self ifStringExists:currentType] == NO)){ [故事添加对象:[项目副本]]; } } }

- (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

【问题讨论】:

    标签: ios objective-c nsmutablearray nsxmlparser


    【解决方案1】:

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

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

    那么你就不会有重复了。

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

    【讨论】:

    • 是的,它与整个字典不完全匹配,它为什么不起作用:3。所以你建议我制作自己的方法并在数组中检查在我的字典中重复的字符串?
    • 我做到了!!! :D 正如你所说,我做了一个小方法来检查整个字典数组中是否没有当前字符串(currentType),并且没有更多重复项:D !!!!!!谢谢你你的炸弹! (我会更新我的问题以将代码提供给其他人并提供帮助:))
    猜你喜欢
    • 1970-01-01
    • 2010-11-06
    • 1970-01-01
    • 1970-01-01
    • 2015-07-15
    • 2018-04-24
    • 2023-03-13
    • 2013-01-27
    • 1970-01-01
    相关资源
    最近更新 更多