远程部署iOS模拟器时IAppVersion类报FormatException求助
解决NSObject转String再转Int的可行方案
核心问题分析
出现System.FormatException的原因是CFBundleVersion对应的字符串无法直接转为整数——可能是字符串包含非数字字符(比如带小数点的版本号,如1.0.2),或是NSObject转字符串时产生了额外格式内容。
可行转换方法
方法1:安全解析+异常兜底
用int.TryParse替代int.Parse,同时处理解析失败的场景,避免崩溃:
public int GetBuild() { var buildObj = NSBundle.MainBundle.ObjectForInfoDictionary("CFBundleVersion"); if (buildObj == null) return 0; // 或业务需求的默认值 string buildStr = buildObj.ToString().Trim(); // 先清理首尾空白字符 if (int.TryParse(buildStr, out int buildNumber)) return buildNumber; // 兼容带小数点的版本号,比如提取最后一段数字 var versionParts = buildStr.Split('.'); if (versionParts.Length > 0 && int.TryParse(versionParts[^1], out int lastPart)) return lastPart; return 0; // 最终兜底值 }
方法2:清理非数字字符后解析
如果CFBundleVersion是带特殊符号的版本格式(如1_0_3、v2.1),先移除所有非数字字符再解析:
public int GetBuild() { string buildStr = NSBundle.MainBundle.ObjectForInfoDictionary("CFBundleVersion")?.ToString() ?? "0"; // 只保留字符串中的数字字符 string pureNumericStr = new string(buildStr.Where(char.IsDigit).ToArray()); return int.TryParse(pureNumericStr, out int result) ? result : 0; }
关键检查项
- 打开项目的
Info.plist文件,确认CFBundleVersion的实际值,确保格式符合你预期的整数或可转换为整数的格式。 - 远程部署模拟器时,同步检查远程环境中
Info.plist的配置,避免因环境差异导致版本值异常。
内容的提问来源于stack exchange,提问作者satish durga
相关产品推荐
相关产品推荐

