热门角色不仅是灵感来源,更是你的效率助手。通过精挑细选的角色提示词,你可以快速生成高质量内容、提升创作灵感,并找到最契合你需求的解决方案。让创作更轻松,让价值更直接!
我们根据不同用户需求,持续更新角色库,让你总能找到合适的灵感入口。
本提示词专门针对iOS开发场景,能够深入解析代理方法的功能原理和应用场景。通过系统化的分析框架,详细阐述代理方法的设计意图、执行流程、参数含义和实际应用,帮助开发者准确理解iOS框架中的委托模式实现机制。输出内容包含技术原理说明、代码示例解析和最佳实践建议,确保技术描述的准确性和实用性,适用于iOS开发学习、代码审查和技术文档编写等多种场景。
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)UITableViewDelegate(可选方法)didDeselectRowAt)。调用时机:
shouldHighlightRowAt → 高亮 → willSelectRowAt → 选择发生 → (必要时)didDeselectRowAt → didSelectRowAt → 取消高亮。tableView.allowsSelection == false:不会调用。tableView(_:willSelectRowAt:) 并返回 nil:选择被阻止,不会调用。allowsMultipleSelection == true):不会自动取消之前选择,可连续触发 didSelectRowAt。isEditing == true):仅在 allowsSelectionDuringEditing == true 时会触发。selectRow(at:animated:scrollPosition:) 进行编程式选择不会自动触发该代理方法;类似地,deselectRow(at:animated:) 也不会自动触发 didDeselectRowAt。执行流程:
indexPath 对应当前数据源状态下的行位置;在单选模式下若已有选中的行,将先触发该行的 didDeselectRowAt,再触发新选中的行的 didSelectRowAt。deselectRow(at:animated:) 以恢复默认的非高亮状态,符合系统交互习惯。参数解析:
tableView: UITableView
allowsMultipleSelection、isEditing)决定处理逻辑。indexPath: IndexPath
section 和 row 组成。IndexPath,避免数据变更导致的错位。tableView.cellForRow(at:) 获取;但该方法仅对当前可见行返回非空。返回值说明:
tableView(_:willSelectRowAt:) 或 tableView(_:shouldHighlightRowAt:) 中控制;didSelectRowAt 仅用于“选择已发生”后的响应。import UIKit
// 假设有一个基于稳定标识的数据模型
struct Item: Hashable {
let id: UUID
let title: String
}
final class ItemsViewController: UIViewController {
@IBOutlet private weak var tableView: UITableView!
// 数据源:按 section 分组的二维数组(或使用 Diffable Data Source)
private var sections: [[Item]] = []
// 防止重复导航的状态标记
private var isNavigating = false
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.allowsSelection = true
tableView.allowsMultipleSelection = false // 单选示例
}
// 根据 IndexPath 安全地获取模型
private func item(at indexPath: IndexPath) -> Item? {
guard sections.indices.contains(indexPath.section),
sections[indexPath.section].indices.contains(indexPath.row) else { return nil }
return sections[indexPath.section][indexPath.row]
}
// 典型的导航处理
private func showDetail(for item: Item) {
// 模拟耗时任务或导航
// 真实项目可 push 到详情控制器并传入 item.id
let detailVC = DetailViewController(itemID: item.id)
navigationController?.pushViewController(detailVC, animated: true)
}
}
// MARK: - UITableViewDataSource
extension ItemsViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int { sections.count }
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { sections[section].count }
func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
if let item = item(at: indexPath) {
cell.textLabel?.text = item.title
cell.selectionStyle = .default // 即便为 .none,didSelectRowAt 仍会被调用(若允许选择)
}
return cell
}
}
// MARK: - UITableViewDelegate
extension ItemsViewController: UITableViewDelegate {
// 可选:禁止某些行被选中(例如禁用奇数行)
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
let isSelectable = indexPath.row % 2 == 0
return isSelectable ? indexPath : nil
}
// 核心:处理选择事件
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// 按系统规范,尽快取消高亮以获得一致的交互体验
tableView.deselectRow(at: indexPath, animated: true)
// 索引模型;避免直接依赖 cell 内容
guard let item = item(at: indexPath) else { return }
// 防抖:避免快速连续点按导致重复导航或业务逻辑重复触发
guard !isNavigating else { return }
isNavigating = true
// 在主线程进行导航;耗时任务放到后台
DispatchQueue.main.async { [weak self] in
self?.showDetail(for: item)
self?.isNavigating = false
}
}
// 可选:多选模式下的取消选择处理(用户在单选模式切换到另一行时也会触发)
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
// 更新状态或统计
}
// 可选:细化高亮行为(不高亮但允许选择时,可返回 false)
func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
return true
}
}
// 示例详情控制器
final class DetailViewController: UIViewController {
private let itemID: UUID
init(itemID: UUID) {
self.itemID = itemID
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
}
实现要求:
indexPath 查询数据模型,避免直接读取 cell 内容以防数据/视图不同步。UITableViewController,默认 clearsSelectionOnViewWillAppear == true 会在界面返回时自动取消选中;如需保留选中状态,将其置为 false 并自行管理。常见问题:
selectRow(at:animated:scrollPosition:) 不会调用 didSelectRowAt。如需统一逻辑,可在选择后手动调用处理函数或统一封装。allowsSelection、isEditing 与 allowsSelectionDuringEditing,以及 willSelectRowAt 是否返回了 nil。indexPath 在回调后可能变得无效。应使用稳定 ID(如模型主键)驱动导航与业务。最佳实践:
didSelectRowAt 中调用 tableView.deselectRow(at:animated:),使交互与系统一致。willSelectRowAt/shouldHighlightRowAt 定制选择策略:前者控制“能否选中”,后者控制“是否高亮”。didDeselectRowAt 做状态同步(如复选 UI 或统计)。IndexPath,以应对快照更新带来的行位置变化。func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)URLSessionDelegate调用时机:
NSURLAuthenticationMethodServerTrust)。NSURLAuthenticationMethodClientCertificate)。URLSessionTaskDelegate.urlSession(_:task:didReceive:completionHandler:),系统会优先调用任务级方法;否则调用本会话级方法。若两者都未实现,则走系统默认处理(可能使用 URLCredentialStorage 或 ATS 的默认信任策略)。执行流程:
URLAuthenticationChallenge,携带保护域(protectionSpace)、建议凭据(proposedCredential)、之前失败次数(previousFailureCount)等信息。completionHandler 一次,指定处理策略(AuthChallengeDisposition)以及相应的凭据(如需要)。previousFailureCount。参数解析:
session:当前触发挑战的会话实例。用于区分不同 URLSession 的策略或状态。challenge:认证挑战的详细信息对象。
protectionSpace:认证范围与方法。
authenticationMethod:常见值包括:
NSURLAuthenticationMethodServerTrust(服务器信任/证书)NSURLAuthenticationMethodHTTPBasic、NSURLAuthenticationMethodHTTPDigestNSURLAuthenticationMethodNTLM、NSURLAuthenticationMethodNegotiate(Kerberos)NSURLAuthenticationMethodClientCertificate(客户端证书)host、port、realm、isProxy、protocol;serverTrust(SecTrust?)在服务器信任挑战中提供。proposedCredential:系统建议使用的凭据(可能来自 URLCredentialStorage)。previousFailureCount:之前失败的次数,用于避免无限重试。failureResponse/error:上次失败的响应或错误(如有)。completionHandler:回调,必须调用一次,传入处理策略与可选凭据。
URLSession.AuthChallengeDisposition:
.useCredential:使用传入的 URLCredential 继续。.performDefaultHandling:交给系统默认处理(ATS/证书信任、凭据存储等)。.cancelAuthenticationChallenge:取消挑战,通常导致请求失败。.rejectProtectionSpace:拒绝当前保护域,让系统尝试其它可用的认证方法(若有)。返回值说明:
completionHandler 的参数决定后续行为。URLCredential 的常见构造:
URLCredential(trust: SecTrust):服务器信任通过。URLCredential(user:password:persistence:):HTTP 基本/摘要认证。URLCredential(identity:certificates:persistence:):客户端证书(SecIdentity + 证书链)。import Foundation
import Security
final class SessionAuthDelegate: NSObject, URLSessionDelegate {
// 在会话层处理认证挑战(服务器证书信任 + HTTP Basic)
func urlSession(_ session: URLSession,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
let method = challenge.protectionSpace.authenticationMethod
switch method {
case NSURLAuthenticationMethodServerTrust:
// TLS 服务器信任(可选:证书/公钥固定)
guard let serverTrust = challenge.protectionSpace.serverTrust else {
completionHandler(.cancelAuthenticationChallenge, nil)
return
}
// 先按系统策略评估(ATS)
var trustError: CFError?
let isTrustedBySystem = SecTrustEvaluateWithError(serverTrust, &trustError)
// 如果你不做固定(pinning),通常选择系统默认处理更安全
// completionHandler(.performDefaultHandling, nil); return
// 示例:证书固定(pinning)
// 将服务端叶子证书与应用内打包的证书(DER)比较
if isTrustedBySystem,
let serverCert = SecTrustGetCertificateAtIndex(serverTrust, 0) {
let serverCertData = SecCertificateCopyData(serverCert) as Data
// 从 Bundle 读取已知的服务器证书(myserver.cer)
guard let certURL = Bundle.main.url(forResource: "myserver", withExtension: "cer"),
let pinnedCertData = try? Data(contentsOf: certURL) else {
completionHandler(.cancelAuthenticationChallenge, nil)
return
}
if serverCertData == pinnedCertData {
// 证书匹配,接受该连接
let credential = URLCredential(trust: serverTrust)
completionHandler(.useCredential, credential)
} else {
// 不匹配,拒绝连接(或 .rejectProtectionSpace 视策略而定)
completionHandler(.cancelAuthenticationChallenge, nil)
}
} else {
// 系统信任评估失败,直接取消
completionHandler(.cancelAuthenticationChallenge, nil)
}
case NSURLAuthenticationMethodHTTPBasic, NSURLAuthenticationMethodHTTPDigest:
// HTTP 基本/摘要认证(401)
// 若系统已有建议凭据(可能来自 URLCredentialStorage),优先使用
if let proposed = challenge.proposedCredential {
completionHandler(.useCredential, proposed)
return
}
// 示例:提供应用内保存的用户名/密码
let username = "user@example.com" // 从安全存储(Keychain)读取
let password = "securePassword" // 从安全存储(Keychain)读取
// 防止无限重试:如果已经失败过,直接取消或提示用户
if challenge.previousFailureCount > 0 {
completionHandler(.cancelAuthenticationChallenge, nil)
return
}
let credential = URLCredential(user: username,
password: password,
persistence: .forSession)
completionHandler(.useCredential, credential)
case NSURLAuthenticationMethodClientCertificate:
// 客户端证书(双向 TLS)
// 需要从 Keychain 读取 SecIdentity 和证书链
// 这里只示意默认处理
completionHandler(.performDefaultHandling, nil)
default:
// 其它方法(NTLM/Kerberos/代理等),如果未特殊处理,交由系统默认
completionHandler(.performDefaultHandling, nil)
}
}
}
// 使用示例:创建 URLSession 并发起请求
let config = URLSessionConfiguration.default
// 可选:开启/配置凭据存储
config.urlCredentialStorage = URLCredentialStorage.shared
let session = URLSession(configuration: config, delegate: SessionAuthDelegate(), delegateQueue: nil)
let url = URL(string: "https://api.example.com/secure")!
let task = session.dataTask(with: url) { data, response, error in
// 处理响应
}
task.resume()
实现要求:
completionHandler,否则请求会挂起或导致崩溃风险。URLSessionConfiguration.background),需要在代理中正确处理认证,否则任务可能失败。常见问题:
previousFailureCount,在错误凭据下不断提供同一凭据,导致循环。应在失败后取消或提示用户。SecTrustEvaluateWithError 可能绕过 ATS 规则,降低安全性。建议先进行系统评估,再做自定义策略。最佳实践:
.performDefaultHandling 与系统信任策略,只有在确有需求时才进行证书/公钥固定。challenge.proposedCredential,结合 URLCredentialStorage 管理凭据,减少重复输入与错误率。调用时机:
执行流程:
参数解析:
返回值说明:
import UIKit
final class ListViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
// 用于控制滚动时的资源消耗(如图片加载、复杂布局计算)
private var isScrollingHeavily = false
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self // UITableViewDelegate 继承自 UIScrollViewDelegate
tableView.dataSource = self
}
private func resumeHeavyWorkIfNeeded() {
guard isScrollingHeavily else { return }
isScrollingHeavily = false
// 恢复图片解码/渲染、启动数据请求等
}
private func pauseHeavyWork() {
isScrollingHeavily = true
// 暂停图片解码/渲染、延迟耗时计算等
}
private func isNearBottom(of scrollView: UIScrollView, threshold: CGFloat = 100) -> Bool {
let contentOffsetBottom = scrollView.contentOffset.y + scrollView.bounds.height
return contentOffsetBottom > (scrollView.contentSize.height - threshold)
}
private func loadMoreIfNeeded(_ scrollView: UIScrollView) {
guard isNearBottom(of: scrollView) else { return }
// 触发“加载更多”,避免在减速期间触发,减少卡顿
// loadMoreData()
}
}
extension ListViewController: UITableViewDelegate, UITableViewDataSource {
// 数据源实现略
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
pauseHeavyWork()
}
func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if decelerate {
// 等待减速结束再恢复重任务,避免掉帧
} else {
// 已停止:可恢复任务并做与“滚动结束”相关的操作
resumeHeavyWorkIfNeeded()
loadMoreIfNeeded(scrollView)
}
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
// 减速结束:此时真正停止
resumeHeavyWorkIfNeeded()
loadMoreIfNeeded(scrollView)
}
}
实现要求:
常见问题:
最佳实践:
用一次输入,快速生成“从原理到落地”的 iOS 代理方法深度解析,覆盖学习、开发、代码评审、技术文档与面试准备等全链路场景。通过标准化的结构输出与可控的技术深度,帮助个人与团队:
借助本提示词,快速搞懂代理方法的触发时机与参数意义,基于示例完成正确实现,并整理为可复用的个人笔记与代码片段。
批量解析关键代理方法,核对实现是否覆盖必要边界与异常路径,输出评审意见与最佳实践清单,推动团队统一规范落地。
一键生成条理清晰的说明、示例与注意事项,直接用于项目Wiki与对外文档,显著缩短资料整理与校对时间。
将模板生成的提示词复制粘贴到您常用的 Chat 应用(如 ChatGPT、Claude 等),即可直接对话使用,无需额外开发。适合个人快速体验和轻量使用场景。
把提示词模板转化为 API,您的程序可任意修改模板参数,通过接口直接调用,轻松实现自动化与批量处理。适合开发者集成与业务系统嵌入。
在 MCP client 中配置对应的 server 地址,让您的 AI 应用自动调用提示词模板。适合高级用户和团队协作,让提示词在不同 AI 工具间无缝衔接。
半价获取高级提示词-优惠即将到期