LoginSignup
6
8

More than 5 years have passed since last update.

【CoreData】あるEntityのあるPropertyの最大値、最小値を取得するのSwift版

Posted at

Objective-C - 【CoreData】あるEntityのあるPropertyの最大値、最小値を取得する - QiitaのSwift2.0版です。

簡単なソースコードだけ。

Persion.swift
import Foundation
import CoreData

class Person: NSManagedObject {

// Insert code here to add functionality to your managed object subclass

}
Person+CoreDataProperties.swift
import Foundation
import CoreData

extension Person {

    @NSManaged var age: NSNumber?
    @NSManaged var name: String?

}
Test.swift
for num in 0...10 {
    if let person = NSEntityDescription.insertNewObjectForEntityForName("Person", inManagedObjectContext: managedObjectContext) as? Person {
        let age = num * 5
        let name = "name_\(num)"
        person.age = age
        person.name = name
    }
}
/// 保存処理        
saveContext()

/// ここからが最大値の取得方法
let expressionAgeName = "maxAge"

/// fetchRequestの生成
let fetchRequest = NSFetchRequest()

/// EntityDescriptionの生成
let entityDescription = NSEntityDescription.entityForName("Person", inManagedObjectContext: managedObjectContext)
fetchRequest.entity = entityDescription

let keyPathExpression = NSExpression(forKeyPath: "age")
let expression = NSExpression(forFunction: "max:", arguments: [keyPathExpression])
let expressionDescription = NSExpressionDescription()
expressionDescription.name = expressionAgeName
expressionDescription.expression = expression
expressionDescription.expressionResultType = NSAttributeType.Integer16AttributeType

fetchRequest.resultType = NSFetchRequestResultType.DictionaryResultType
fetchRequest.propertiesToFetch = [expressionDescription]

do {
    let results = try managedObjectContext.executeFetchRequest(fetchRequest)
    if let maxAge = results.first?.valueForKey(expressionAgeName) as? Int {
        print("maxAge = \(maxAge)")
    }
} catch let error {
    print(error)
}

こんな感じで取得できました。

補足

最小値が欲しい場合は

let expression = NSExpression(forFunction: "max:", arguments: [keyPathExpression])

の部分を

let expression = NSExpression(forFunction: "min:", arguments: [keyPathExpression])

にすれば良いです。

他にも平均値のavarage:や合計のsum:、数のcount:と指定できる値があります。

終わりに

やはり僕はSwiftの方が好きです。

6
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
8