fake va_list in ARC

后端 未结 2 1616
臣服心动
臣服心动 2020-12-03 08:07

I need to create in an iOS application a fake va_list to pass to a NSString initWithFormat:arguments: function, this is my code:

NS         


        
2条回答
  •  悲&欢浪女
    2020-12-03 08:35

    Its possible if you are willing to add a little bit of swift to your project!

    The important bit is the mapping of NSArray to [CVarArgType] which is the swift equivalent for va_list. If you try to cast [AnyObject] to [CVarArgType] you cause run time crashes, but with the map we can explicitly make the needed list.

    The rest of the code is the wrapper I made so that I can call this from obj-c. You could make a wrapper for any obj-c function that you want to call in this way.

    @objc class StringFormat: NSObject {
        class func format(key: String, args: [AnyObject]) -> String {
            let locArgs: [CVarArgType] = args.map({ (arg: AnyObject) -> CVarArgType in
                if let iArg = (arg is NSNumber ? arg.intValue : nil) {
                    return iArg
                }
                return arg as! CVarArgType
            });
            return String(format: key, arguments: locArgs)
        }
    }
    

提交回复
热议问题