Coder221
Coder221

Reputation: 1433

Filtering out integer from NSManaged object

I have the following core data property

@NSManaged public var part: [Int]?

and it may contain 0 or 1 or both. I am trying to filter out the part which contains 1 and did this

 fetchRequest.predicate = NSPredicate(format:"part == %@", 1)

But I am getting the error

Thread 1: EXC_BAD_ACCESS (code=1, address=0x1)

if I do the above. What am I doing wrong here? Thanks in advance.

Upvotes: 0

Views: 336

Answers (4)

Rohit Makwana
Rohit Makwana

Reputation: 4875

You can use filter for that (Swift 4.2)

let arrInt = [1,0,0,0,0,1,0,1,1,0,0,0,0,0,1,0,0,1,0,0,1]

 let ones = arrInt.filter({$0 == 1})

 print(ones)

Output:

 [1, 1, 1, 1, 1, 1, 1]

Upvotes: 0

Bhavik Modi
Bhavik Modi

Reputation: 1565

You can achieve the same using Predicate too: Use the following code:

let part = [1,3,4,7,2,1,4,3,1,5,6,7,1,3,4,8,9,1]
let predicate = NSPredicate(format: "SELF == %d",1)
let result = (part as NSArray).filtered(using: predicate)
print(result)

Output:

[1, 1, 1, 1, 1]

Upvotes: 0

PGDev
PGDev

Reputation: 24341

The code you've written, i.e.

fetchRequest.predicate = NSPredicate(format:"part == %@", 1)

In the above code, you're trying to filter all the fetched rows based on whether part is 1 or not. So basically here you're using part as an Int. But as per the declaration, part is an array [Int].

It will definitely throw an exception.

You need to filter each row after fetching like:

let filteredPart = part.filter({ $0 == 1 })

Upvotes: 1

BhargavR
BhargavR

Reputation: 1133

Simply use below code :

let filteredArray = part.filter() { $0 == 1 }
print(filteredArray.count)

You'll get the desired result. Hope this helps.

Upvotes: 1

Related Questions