检查NSMutableArray中是否存在项目

时间:2013-03-14 20:13:00

标签: ios objective-c 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是否已经存在?

3 个答案:

答案 0 :(得分: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 :(得分:1)

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

答案 2 :(得分:0)

使用for循环

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