2013-03-14 76 views
-4

我有一个保存自定义对象的NSMutableArray。其内容示例如下:检查项目是否存在于一个NSMutableArray

2013-03-14 20:06:23.895 MyMusicLibrary[1667:c07] myLibrary: (
    { 
    artist = "Green Day"; 
    id = 1421768; 
    name = "American Idiot"; 
    releasedate = "21 Sep 2004"; 
    runningtime = "57.53"; 
    tracks = "1: American Idiot\n2: Jesus of Suburbia\n3: Holiday/Boulevard Of Broken Dreams\n4: Are We The Waiting/St. Jimmy\n5: Give Me Novacaine/She's A Rebel\n6: Extraordinary Girl/Letterbomb\n7: Wake Me Up When September Ends\n8: Homecoming\n9: Whatsername\n"; 
    trackscount = 9; 
    type = 1; 
}, 
    { 
    artist = Bastille; 
    id = 309124896; 
    name = "Bad Blood"; 
    releasedate = "1 Mar 2013"; 
    runningtime = "43.98"; 
    tracks = "1: Pompeii\n2: Things We Lost in the Fire\n3: Bad Blood\n4: Overjoyed\n5: These Streets\n6: Weight of Living, Pt. II\n7: Icarus\n8: Oblivion\n9: Flaws\n10: Daniel in the Den\n11: Laura Palmer\n12: Get Home\n13: Weight of Living, Pt. I\n"; 
    trackscount = 13; 
    type = 1; 
}, 
    { 
    artist = "Lacuna Coil"; 
    id = 2025689; 
    name = Comalies; 
    releasedate = "16 Oct 2012"; 
    runningtime = "51.75"; 
    tracks = "1: Swamped\n2: Heaven's a Lie\n3: Daylight Dancer\n4: Humane\n5: Self Deception\n6: Aeon\n7: Tight Rope\n8: The Ghost Woman and the Hunter\n9: Unspoken\n10: Entwined\n11: The Prophet Said\n12: Angels Punishment\n13: Comalies\n"; 
    trackscount = 13; 
    type = 1; 
} 
) 

我该如何循环访问数组,以检查ID是否已经存在?

+1

此外,这是既不iPhone-也不特定的Xcode-。我讨厌标签滥用! – 2013-03-14 20:15:24

+3

怎么了downvotes?老兄有一个值得质疑的问题,不管标签是否被“滥用”。我们都是初学者,一次是人。不需要任何尖刻的评论,他明确地问过如何循环数组,他不需要被告知使用循环。 – Justin 2013-03-14 20:24:38

+2

@JustinAmberson @JustinAmberson即使我没有倒下,我认为任何人选择他是否完全没问题,如果他认为一个问题'没有显示任何研究努力'等。没有必要告诉我们,如果你有不同的意见。只需点击向上箭头即可表达该意见。 – Till 2013-03-14 20:33:54

回答

6

您不会说明阵列中有什么对象。以下应在一般工作:

NSMutableArray *array = ... // the array with the objects 
id keyToFind = ... // the key to locate 
for (id object in array) { 
    id key = [object valueForKey:@"id"]; 
    if ([key isEqual:keyToFind]) { 
     // found 
    } 
} 

使用每个id可以用更具体的类别根据需要进行更换。

+1

非常感谢!工作很好。 – Cheese1223 2013-03-14 20:52:59

1

循环遍历数组并检查每次迭代中ID是否为当前ID。如果是,则存在该ID。如果不是,则数组中不存在该ID。

0

随着for

NSInteger idToCheck = 12345; 
for (MyObject *obj in myArray){ 
    if (obj.id == idToCheck) { 
     //do something here 
    } 
} 
相关问题