简体   繁体   中英

How to get the displayname of a CIFilter?

I'm trying to get a list of the display names of the CIFilters. Have found this site which has the constants that should give the name (with other info), but the code below is not working.

Console output:

here 01
here 02
*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<CIAccordionFoldTransition 0x7a672dc0> valueForUndefinedKey:]: this class is not key value coding-compliant for the key CIAttributeFilterName.'

My code:

func getCIFilterName(filterName: String) -> String{
    var res = "abc"

    let fltr = CIFilter(name:filterName)
    println("here 01")
    if contains(fltr.attributes().keys, kCIAttributeFilterDisplayName){
        println("here 02")
        res = fltr.valueForKey(kCIAttributeFilterDisplayName) as String
    }
    println("here 03")

    return res
}

The attributes method returns a dictionary. So much simpler to do it like this:

func getCIFilterName(filterName: String) -> String {
    var res = "abc"
    let fltr = CIFilter(name:filterName)
    if let disp = fltr.attributes()[kCIAttributeFilterDisplayName] as? String {
        res = disp
    }
    return res
}

But I do not like your trick of returning a false value "abc" if we fail. This is what Optionals are for - to get us away from "magic values" of this sort. So rewrite like this:

func getCIFilterName(filterName: String) -> String! {
    var res : String! = nil
    let fltr = CIFilter(name:filterName)
    if let disp = fltr.attributes()[kCIAttributeFilterDisplayName] as? String {
        res = disp
    }
    return res
}

Do not forget, however, to check the returned value against nil, or you'll crash if you try to use it for anything (if it is nil).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM