【问题标题】:pulling unique values from an array of custom objects从自定义对象数组中提取唯一值
【发布时间】:2011-09-28 15:29:24
【问题描述】:

我有一个自定义对象的数组列表。每个对象都包含一个我需要提取的值,claimNO,但不是唯一值,这意味着说 5 个对象可能具有相同的 claimNO。

我需要做的是创建一个只有唯一声明NO 的数组。我需要在选择器中显示这个并且不能有任何重复的claimNO。

我的对象:

@interface ClaimCenterClaim : NSObject 
{
    NSNumber *claimID;
    NSString *claimNO;
    NSNumber *coid;
    NSString *eventDates;
}

@property (nonatomic, retain) NSNumber *claimID;
@property (nonatomic, retain) NSString *claimNO;
@property (nonatomic, retain) NSNumber *coid;
@property (nonatomic, retain) NSString *eventDates;

@end

对我来说,这应该可行:

            NSMutableDictionary *ClaimCenterClaimNOList = [[NSMutableDictionary alloc] init];

            int count01 = [sortedClaimList count];
            for (int i = 0; i < count01; i++) 
            {
                claimCenterClaim = [sortedClaimList objectAtIndex:i];

                if ([ClaimCenterClaimNOList objectForKey:claimCenterClaim.claimID] != claimCenterClaim.claimNO)
                {
                    NSLog(@"entered the bloody loop");
                    [ClaimCenterClaimNOList setObject:claimCenterClaim.claimNO forKey:claimCenterClaim.claimID];
                }
                else
                    NSLog(@"did not add value");
            }

但我的“[ClaimCenterClaimNOList objectForKey:claimCenterClaim.claimID]”的值始终为空,直到 if 语句之后。

如果我有一个 claimID 值,我不能只检查字典中的键值是否已经存在,如果不存在,添加它吗?

我想避免需要遍历 ClaimCenterClaimNOList 字典(在循环中创建一个循环)。但是我知道密钥,我不能只看字典中是否已经存在该密钥吗?

编辑:不正确的逻辑

我的 claimID 值是唯一的,所以如果一个 claimID 已经添加到字典中,我会检查我的字典。由于 claimID 是唯一的,因此它从未找到匹配项。我切换了搜索,现在正在工作。这是正确的代码:

             int count01 = [sortedClaimList count];
            for (int i = 0; i < count01; i++) 
            {                    
                claimCenterClaim = [sortedClaimList objectAtIndex:i];

                NSLog(@"lets see before: claimCenterClaim.claimiD: %@ the object: %@",claimCenterClaim.claimID, [ClaimCenterClaimNOList objectForKey:claimCenterClaim.claimID]);

                if ([ClaimCenterClaimNOList objectForKey:claimCenterClaim.claimNO] == nil)
                {
                    NSLog(@"not in the dictionary");
                    [ClaimCenterClaimNOList setObject:claimCenterClaim.claimID forKey:claimCenterClaim.claimNO];
                }
                else
                {
                    NSLog(@"it works, it is in the dictionary");
                }
            }

【问题讨论】:

    标签: objective-c nsdictionary


    【解决方案1】:

    偶数点,对于objectForKey,检查nil 以确定缺少密钥。

    此外,您可以将声明数组放入似乎更接近所需行为的NSSet 中。但我不确定,如果您只想访问任何给定索赔编号的一个或所有索赔。

    我认为明智的设计您正在做的事情会奏效,但将您的索赔类别概括为包含任何给定索赔编号的所有索赔。保留您的字典,索赔编号键将访问附加到唯一索赔编号的所有给定索赔。

    【讨论】:

    • 感谢您提供有关搜索 nil 的提示,它有所帮助。另外,我从未使用过 NSSet,不确定它的用途,但我会调查一下,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-13
    • 2019-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多