Converting NSArray Contents to a varargs (With ARC) For Use With NSString initWithFormat

前端 未结 6 923
广开言路
广开言路 2021-02-19 13:43

We have some code today that takes an NSArray and passes it as a argument list to -[NSString initWithFormat:arguments] and we\'re trying to get this to work with ARC. Here\'s th

6条回答
  •  日久生厌
    2021-02-19 14:32

    Cannot find a way to do this obj-c but a swift helper class finally got this working (my whole project is obj-c except this class)

    @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)
        }
    }
    

    There is some magic going on, to do with how [CVarArgType] doesn't behave like a normal array - but this works in the flexible cross architecture way you expect it to.

提交回复
热议问题