Search code examples
ioscore-datansarraynsdictionarynsset

Create NSSet using a predicate from an NSArray of NSDictionaries


I am trying to create a NSSet from an NSArray of NSDictionaries. However every time the thread hits my NSSet code it throws a BAD ACCESS error and my app falls over.

NSSet *matchingItems = [insProject.ins filteredSetUsingPredicate:[NSPredicate predicateWithFormat:@"dpc == %@", dpc]];

dpc == 2

when I log insProject.ins this is what I get.

2013-11-16 16:53:27.148 myAPP[7979:907] Relationship 'ins' on managed object (0x1d570b00) <insProject: 0x1d570b00> (entity: insProject; id: 0x1d575830 <x-coredata://XXXXXXXXXXX/insProject/p2> ; data: <fault>) with objects {(
    <ins: 0x1d59cf60> (entity: ins; id: 0x1d59c040 <x-coredata://XXXXXXXXXXX/ins/p50> ; data: {
    dpc = 11;
}),
    <ins: 0x1d59cbe0> (entity: ins; id: 0x1d59bf80 <x-coredata://28BFA6C4-F20F-445D-AD93-2CA028303C28/ins/p38> ; data: {
    dpc = 4;
}),
    <ins: 0x1d59cc80> (entity: ins; id: 0x1d59bfa0 <x-coredata://28BFA6C4-F20F-445D-AD93-2CA028303C28/ins/p40> ; data: {
    dpc = 7;
}),
    <ins: 0x1d59c900> (entity: ins; id: 0x1d59bf50 <x-coredata://28BFA6C4-F20F-445D-AD93-2CA028303C28/ins/p35> ; data: {
    dpc = 9;

}),
    <ins: 0x1d59cd80> (entity: ins; id: 0x1d59bfd0 <x-coredata://28BFA6C4-F20F-445D-AD93-2CA028303C28/ins/p43> ; data: {
    dpc = 16;
}),
    <ins: 0x1d59cf20> (entity: ins; id: 0x1d59c030 <x-coredata://28BFA6C4-F20F-445D-AD93-2CA028303C28/ins/p49> ; data: {
    dpc = 2;
})
)}

As you can see, there is an item in the array that has dpc == 2 but this NSSet line of code just goes crazy when it tries to run.


Solution

  • It looks like you have a type mismatch between the format string of your NSPredicate and the value of dpc that you pass to it: the format string with %@ expects an object, so passing a primitive type to it triggers undefined behavior.

    If dpc is an int, change the format string to @"dpc == %d"; it should fix the problem. Alternatively, make dpc an NSNumber, and keep the %@ format:

    NSNumber *dpc = @2; // This is the new syntax for [NSNumber numberWithInt:2]