NSNotFound

1.在数组或者字典中查找元素时,没有查到系统用NSNotFound表示。比如下面例子,应该养成这种编程习惯,可以减少因为’超标’而闪退的情况。
if ([self.departmentNameArray indexOfObject: self.applicationcreatorModel.departmentName] == NSNotFound)

 

转载于:https://www.cnblogs.com/cchHers/p/8712507.html

- (void)loginQROpenApp:(NSString *)json { NSRange range = [json rangeOfString:@"BM_ANGEL:qrcode_scan_oppenapp#"]; NSMutableString *mstring = [NSMutableString stringWithString:json]; NSString *result = [json substringFromIndex:range.length]; NSString *appid = [self subAppid:result]; DFBLog(@"appid=======%@",appid); NSString *params = [self params:result]; NSString *correctedJSONString = [params stringByReplacingOccurrencesOfString:@"'" withString:@"\""]; NSDictionary *content = [correctedJSONString mj_JSONObject]; DFBLog(@"appid=======%@",appid); [self openApp:appid withName:@"" withUrl:@"" withParmas:content]; } - (NSString *)params:(NSString *)ppidString { // 找到params={...}的位置 NSRange paramsRange = [ppidString rangeOfString:@"params={"]; if (paramsRange.location != NSNotFound) { paramsRange.location += 7; // 跳过"params={" // 查找闭合的"}" NSRange closeBraceRange = [ppidString rangeOfString:@"}" options:NSLiteralSearch range:NSMakeRange(paramsRange.location, ppidString.length - paramsRange.location)]; if (closeBraceRange.location != NSNotFound) { // 截取params里面的内容 NSString *paramsContent = [ppidString substringWithRange:NSMakeRange(paramsRange.location, closeBraceRange.location - paramsRange.location + 1)]; return paramsContent; } return @""; } else { return @""; } } - (NSString *)subAppid:(NSString *)ppidString { NSRange ppidRange = [ppidString rangeOfString:@"appid="]; if (ppidRange.location != NSNotFound) { // 截取从 ppid= 之后的子字符串 NSString *ppidValueWithPrefix = [ppidString substringFromIndex:ppidRange.location + ppidRange.length]; // 查找 # 的位置(如果有) NSRange hashRange = [ppidValueWithPrefix rangeOfString:@"#"]; if (hashRange.location != NSNotFound) { // 截取到 # 之前的部分 NSString *ppidValue = [ppidValueWithPrefix substringToIndex:hashRange.location]; return ppidValue; } else { // 如果没有 #,则整个 ppidValueWithPrefix 就是我们要的值 return ppidValueWithPrefix; } } else { return @""; } } - (NSDictionary *)parseParamsString:(NSString *)paramsString { NSMutableDictionary *dict = [NSMutableDictionary dictionary]; // 这里为了简单起见,我们假设 paramsString 是正确的,并且格式固定 // 在实际使用中,您可能需要使用更健壮的解析方法,比如 NSJSONSerialization 或者正则表达式 NSArray *components = [paramsString componentsSeparatedByString:@","]; for (int i = 0; i < components.count; i += 2) { NSString *key = [components[i] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; NSString *value = [components[i+1] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; // 去除尾部的单引号 value = [value substringToIndex:value.length - 1]; dict[key] = value; } return dict; }
06-12
//先遍历,去掉已收到最新已读状态的会话id;或者轮询次数大于10次的会话id NSMutableIndexSet *indexSet = [NSMutableIndexSet indexSet]; //创建一个新数组用于遍历,避免遍历期间修改,导致崩溃 // NSArray *tempArray = [NSArray arrayWithArray:self.waitToUpdateDialoguesArray]; YYThreadSafeArray *tempArray = [YYThreadSafeArray arrayWithArray:self.waitToUpdateDialoguesArray]; // @synchronized (tempArray) { //开始遍历 for (NSString *dialogueId in tempArray) { //增加判断,避免indexOfObject越界 if ([dialogueId integerValue] < self.dialogueCheckCountDic.count) { //对应的会话在当前连接中,是否收到了headline消息 if ([self.didReceiveIQMessageDialogueIdArray containsObject:dialogueId] || //或者轮询次数大于10次 [[self.dialogueCheckCountDic objectForKey:dialogueId] integerValue]>10) { if ([self.waitToUpdateDialoguesArray indexOfObject:dialogueId] != NSNotFound) { [indexSet addIndex:[self.waitToUpdateDialoguesArray indexOfObject:dialogueId]]; } } } } //如果有需要移除的,就移除掉 //并且确保临时数组与waitToUpdateDialoguesArray数量相同,避免被修改后越界修改 if (indexSet.count >0 && tempArray.count == self.waitToUpdateDialoguesArray.count) { [self.waitToUpdateDialoguesArray removeObjectsAtIndexes:indexSet]; } } 你是ios专家, 我的app在运行中发生错误, xcode定位到以上代码发生错误并提示[NSArray initWithArray:range:copyItems:]: range {0, 2} extends beyond bounds for empty array错误, 请分析这个错误原因
07-23
import Cocoa @main class AppDelegate: NSObject, NSApplicationDelegate { private var writableXMLURL: URL! // 可写的副本路径 private let bundleFileName = "config.xml" // Bundle 中原始文件名 func applicationDidFinishLaunching(_ notification: Notification) { setupMenu() copyXMLFromBundleToWritableLocation() } // MARK: - 菜单设置 func setupMenu() { let menu = NSMenu() let updateItem = NSMenuItem(title: "Update XML Content", action: #selector(updateXML), keyEquivalent: "u") updateItem.keyEquivalentModifierMask = .command let showItem = NSMenuItem(title: "Show Current XML", action: #selector(showXMLContent), keyEquivalent: "s") showItem.keyEquivalentModifierMask = .command menu.addItem(updateItem) menu.addItem(showItem) menu.addItem(NSMenuItem.separator()) menu.addItem(withTitle: "Quit", action: #selector(quit), keyEquivalent: "q") let appMenu = NSMenuItem() appMenu.submenu = menu NSApp.mainMenu = NSMenu() NSApp.mainMenu?.addItem(appMenu) } // MARK: - 从 Bundle 复制 XML 到可写位置 func copyXMLFromBundleToWritableLocation() { // 获取目标路径:~/Library/Application Support/com.yourcompany.AppName/config.xml guard let appSupport = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first else { return } let bundleID = Bundle.main.bundleIdentifier ?? "com.example.DefaultApp" writableXMLURL = appSupport.appendingPathComponent("$bundleID/$bundleFileName)") // 确保目录存在 try? FileManager.default.createDirectory(at: writableXMLURL.deletingLastPathComponent(), withIntermediateDirectories: true) // 如果可写位置还没有该文件,则从 Bundle 复制过去 if !FileManager.default.fileExists(atPath: writableXMLURL.path) { guard let bundledFileURL = Bundle.main.url(forResource: "config", withExtension: "xml") else { print("❌ 未在 App Bundle 中找到 config.xml") return } do { try FileManager.default.copyItem(at: bundledFileURL, to: writableXMLURL) print("✅ 已从 Bundle 复制 config.xml 到: $writableXMLURL.path)") } catch { print("❌ 复制失败: $error)") } } else { print("📄 使用已有可写配置文件: $writableXMLURL.path)") } } // MARK: - 动态更新 XML 内容 @objc func updateXML() { // 1. 读取当前可写 XML 文件 guard var content = try? String(contentsOf: writableXMLURL, encoding: .utf8) else { print("❌ 无法读取可写 XML 文件") return } // 2. 使用正则提取当前 version 并递增 let versionPattern = #"<version>(.*?)</version>"# let regex = try! NSRegularExpression(pattern: versionPattern, options: []) let nsString = content as NSString let range = NSRange(location: 0, length: nsString.length) var newVersion = "1.0" if let match = regex.firstMatch(in: content, range: range) { // 使用 match.range(at: 1) 获取捕获组(即版本号部分)的 NSRange let capturedRange = match.range(at: 1) if capturedRange.location != NSNotFound, capturedRange.length > 0 { // 使用 NSString 的 substring 方法提取文本 let oldVersionStr = nsString.substring(with: capturedRange) if let oldVersion = Double(oldVersionStr) { newVersion = String(format: "%.1f", oldVersion + 0.1) } else { print("⚠️ 无法解析版本号: $oldVersionStr)") } } } print("🔧 新版本号: $newVersion)") // 3. 生成新时间 let formatter = DateFormatter() formatter.timeStyle = .medium formatter.dateStyle = .short let nowStr = formatter.string(from: Date()) // 4. 替换 version 和 lastModified 字段 content = content .replacingOccurrences(of: #"<version>.*?</version>"#, with: "<version>$newVersion)</version>", options: .regularExpression) .replacingOccurrences(of: #"<lastModified>.*?</lastModified>"#, with: "<lastModified>$nowStr)</lastModified>", options: .regularExpression) // 5. 写回可写文件 do { try content.write(to: writableXMLURL, atomically: true, encoding: .utf8) print("✅ 成功更新并保存 XML:\n$content)") } catch { print("❌ 写入失败: $error)") } } // MARK: - 显示当前 XML 内容 @objc func showXMLContent() { guard let content = try? String(contentsOf: writableXMLURL, encoding: .utf8) else { print("❌ 无法读取文件") return } let alert = NSAlert() alert.messageText = "Current Writable XML" alert.informativeText = content alert.alertStyle = .informational alert.runModal() } @objc func quit() { NSApp.terminate(nil) } } 我这个是不是没写界面啊?运行出来什么也没有,能不能再额外加点可视化或者打印,让我知道具体修改到了文件没有
最新发布
12-03
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值