热门角色不仅是灵感来源,更是你的效率助手。通过精挑细选的角色提示词,你可以快速生成高质量内容、提升创作灵感,并找到最契合你需求的解决方案。让创作更轻松,让价值更直接!
我们根据不同用户需求,持续更新角色库,让你总能找到合适的灵感入口。
本提示词专为iOS开发者设计,能够根据函数名称和功能描述生成专业、规范的弃用警告。通过结构化分析函数的技术特性和替代方案,确保生成的警告信息既符合苹果官方标准又具备实际指导价值。生成的警告包含版本标记、替代建议、迁移指南等关键要素,帮助开发者平滑过渡到新的API实现,提升代码维护性和兼容性。
以下代码仅展示弃用标注与文档注释,示例中的替代 API 名称与签名在“替代方案详细描述”中定义。请根据你的命名空间/可见性进行调整。
/// 同步在主线程从网络 URL 加载 UIImage 的旧接口。
/// - Warning: 已弃用。该方法会阻塞主线程,导致滚动卡顿与启动延迟,且缺乏超时、取消与磁盘缓存等能力。
/// - Deprecated: 请迁移至 `loadImage(url:cachePolicy:priority:timeout:)` (async/await)
/// 或 `loadImage(url:cachePolicy:priority:completion:)`(回调版),并在 UI 使用占位图与可取消的加载任务。
@available(*, deprecated, message: "Synchronous image loading on the main thread is deprecated. Use the async 'loadImage(url:cachePolicy:priority:timeout:)' or the completion-based variant with cancellation and placeholder.")
public func loadImageSync(url: URL, cache: Bool) -> UIImage
如果你已确定新的统一 API 名称,可增加 renamed 指示:
@available(*, deprecated, renamed: "loadImage(url:cachePolicy:priority:timeout:)")
public func loadImageSync(url: URL, cache: Bool) -> UIImage
头文件声明示例:
/// 同步在主线程从网络 URL 加载 UIImage 的旧接口。
/// Deprecated: 请迁移至 -loadImageWithURL:cachePolicy:priority:timeout:completion:
/// 或 Swift async 版本,并使用占位图与可取消任务。
- (UIImage *)loadImageSyncWithURL:(NSURL *)url
cache:(BOOL)cache
__attribute__((deprecated("Synchronous image loading on the main thread is deprecated. Use -loadImageWithURL:cachePolicy:priority:timeout:completion: or the Swift async API.")));
如需采用 Apple 提供的标准宏并绑定系统版本,请在确定版本后替换如下(示例版本号仅作占位,需按你项目策略填写):
- (UIImage *)loadImageSyncWithURL:(NSURL *)url
cache:(BOOL)cache
API_DEPRECATED("Synchronous image loading is deprecated. Use -loadImageWithURL:cachePolicy:priority:timeout:completion:.", ios(11.0, 17.0));
结论:该接口不符合异步优先的 API 设计原则,也不满足现代网络加载在性能、可靠性与可维护性上的要求。
目标:迁移至“异步加载 + 可取消并发下载 + URLCache 磁盘缓存 + 占位图”的方案,支持优先级与取消,提供 Swift 并发与回调两种接口。
示例 API 设计:
public enum ImageError: Error {
case invalidResponse
case decodeFailed
}
public final class ImageMemoryCache {
public static let shared = ImageMemoryCache()
private let cache = NSCache<NSURL, UIImage>()
private init() {}
public func image(for url: URL) -> UIImage? { cache.object(forKey: url as NSURL) }
public func insert(_ image: UIImage, for url: URL) { cache.setObject(image, forKey: url as NSURL) }
}
@discardableResult
public func configureURLCache(memoryMB: Int = 64, diskMB: Int = 256) -> URLCache {
let urlCache = URLCache(
memoryCapacity: memoryMB * 1024 * 1024,
diskCapacity: diskMB * 1024 * 1024,
diskPath: "ImageURLCache"
)
URLCache.shared = urlCache
return urlCache
}
/// 异步加载图片,使用 URLCache 与内存缓存,支持超时与优先级。
public func loadImage(
url: URL,
cachePolicy: URLRequest.CachePolicy = .returnCacheDataElseLoad,
priority: Float = URLSessionTask.defaultPriority, // 0.0~1.0
timeout: TimeInterval = 30
) async throws -> UIImage {
// 1) 先查内存缓存
if let cached = ImageMemoryCache.shared.image(for: url) { return cached }
// 2) 构建请求,启用 URLCache
var request = URLRequest(url: url, cachePolicy: cachePolicy, timeoutInterval: timeout)
// 3) 从 URLCache 命中(如果有)
if let cachedResponse = URLCache.shared.cachedResponse(for: request),
let image = UIImage(data: cachedResponse.data) {
ImageMemoryCache.shared.insert(image, for: url)
return image
}
// 4) 网络请求(支持取消)
let session = URLSession(configuration: .default)
let (data, response) = try await session.data(for: request, delegate: nil)
guard let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode) else {
throw ImageError.invalidResponse
}
guard let image = UIImage(data: data) else {
throw ImageError.decodeFailed
}
// 5) 写入缓存
ImageMemoryCache.shared.insert(image, for: url)
let cached = CachedURLResponse(response: response, data: data)
URLCache.shared.storeCachedResponse(cached, for: request)
// 6) 设置任务优先级(通过 task value 调整,或使用 URLSessionDataTask 的 priority;async/await 由 Task 优先级影响)
// 在 async/await 下,通常通过创建 Task(priority:) 调用本函数进行间接控制。
return image
}
UI 便捷封装(占位图 + 取消):
public protocol Cancellable {
func cancel()
}
extension Task: Cancellable {}
public extension UIImageView {
/// 为 UIImageView 提供占位图与可取消的加载任务
@discardableResult
func setImage(
from url: URL,
placeholder: UIImage? = nil,
cachePolicy: URLRequest.CachePolicy = .returnCacheDataElseLoad,
priority: TaskPriority = .medium,
timeout: TimeInterval = 30
) -> Cancellable {
self.image = placeholder
let task = Task(priority: priority) { [weak self] in
do {
let image = try await loadImage(url: url, cachePolicy: cachePolicy, timeout: timeout)
// 在主线程更新 UI
await MainActor.run { self?.image = image }
} catch {
// 可按需记录或回退
}
}
return task
}
}
取消示例(如在 UITableViewCell.prepareForReuse 中):
private var imageTask: Cancellable?
func configure(with url: URL) {
imageTask?.cancel()
imageTask = imageView.setImage(from: url, placeholder: UIImage(named: "placeholder"))
}
typedef void(^ImageLoadCompletion)(UIImage * _Nullable image, NSError * _Nullable error);
@interface ImageLoader : NSObject
+ (NSURLSessionDataTask *)loadImageWithURL:(NSURL *)url
cachePolicy:(NSURLRequestCachePolicy)cachePolicy
priority:(float)priority // 0.0~1.0
timeout:(NSTimeInterval)timeout
completion:(ImageLoadCompletion)completion;
@end
@implementation ImageLoader
+ (NSURLSessionDataTask *)loadImageWithURL:(NSURL *)url
cachePolicy:(NSURLRequestCachePolicy)cachePolicy
priority:(float)priority
timeout:(NSTimeInterval)timeout
completion:(ImageLoadCompletion)completion
{
// 内存缓存(可用 NSCache 单例)
static NSCache<NSURL *, UIImage *> *memCache;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
memCache = [NSCache new];
});
UIImage *cached = [memCache objectForKey:url];
if (cached) {
if (completion) { completion(cached, nil); }
return nil; // 无需任务
}
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:cachePolicy timeoutInterval:timeout];
// URLCache 命中
NSCachedURLResponse *cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request];
if (cachedResponse) {
UIImage *img = [UIImage imageWithData:cachedResponse.data];
if (img) {
[memCache setObject:img forKey:url];
if (completion) { completion(img, nil); }
return nil;
}
}
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) { if (completion) completion(nil, error); return; }
NSHTTPURLResponse *http = (NSHTTPURLResponse *)response;
if (![http isKindOfClass:[NSHTTPURLResponse class]] || http.statusCode < 200 || http.statusCode >= 300) {
if (completion) completion(nil, [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorBadServerResponse userInfo:nil]);
return;
}
UIImage *img = [UIImage imageWithData:data];
if (!img) {
if (completion) completion(nil, [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadCorruptFileError userInfo:nil]);
return;
}
[memCache setObject:img forKey:url];
NSCachedURLResponse *toStore = [[NSCachedURLResponse alloc] initWithResponse:response data:data];
[[NSURLCache sharedURLCache] storeCachedResponse:toStore forRequest:request];
if (completion) completion(img, nil);
}];
task.priority = priority; // 0.0~1.0
[task resume];
return task;
}
@end
要点:
如需进一步将下载队列、重试、退避、解码隔离(解码放入后台队列)等能力产品化,可在现有异步 API 基础上迭代扩展;以上替代方案已满足“异步加载、并发下载、可取消、磁盘缓存与占位图”的核心目标。
| 项目 | 内容 |
|---|---|
| 函数名 | legacyHTTPGet(url:timeout:completion:) |
| 所属平台 | macOS |
| 现有功能 | 以 HTTP GET 拉取 JSON;同步请求+RunLoop 依赖;支持超时与简单重试;通过 completion 回调返回结果 |
| 已知问题 | 无严格 TLS 校验;无 HTTP/2 明确支持;不可取消;无网络指标上报;在代理/重定向场景易出错;错误模型不统一 |
| 主要调用场景 | 拉取远端 JSON 配置/数据,轻量网络请求 |
// MARK: - Deprecated API
@available(*, deprecated, message: "Use URLSession-based APIs. Prefer async/await: fetchJSON(from:timeout:retries:session:) or Combine: fetchJSONPublisher(from:timeout:session:). See migration guide.")
public func legacyHTTPGet(url: URL,
timeout: TimeInterval,
completion: @escaping (Result<Any, Error>) -> Void)
可选:如果需要在文档中显式隐藏旧实现,还可搭配不推荐使用标注
@available(*, unavailable, message: "Replaced by fetchJSON(from:timeout:retries:session:) (async/await) or fetchJSONPublisher(from:timeout:session:) (Combine).")
public func legacyHTTPGet(url: URL,
timeout: TimeInterval,
completion: @escaping (Result<Any, Error>) -> Void)
// Legacy declaration (Objective-C)
- (void)legacyHTTPGetWithURL:(NSURL *)url
timeout:(NSTimeInterval)timeout
completion:(void (^_Nonnull)(id _Nullable json, NSError * _Nullable error))completion
__attribute__((deprecated("Use URLSession-based APIs: Swift async fetchJSON(from:timeout:retries:session:) or Combine fetchJSONPublisher(from:timeout:session:). See migration guide.")));
说明:
目标:迁移至 URLSession,提供
public enum NetworkError: Error {
case cancelled
case transport(URLError)
case invalidResponse
case httpStatus(Int, Data?)
case decoding(Error)
case timeout
}
struct RetryPolicy {
let maxAttempts: Int
let baseDelay: TimeInterval
let maxDelay: TimeInterval
static let `default` = RetryPolicy(maxAttempts: 2, baseDelay: 0.5, maxDelay: 2.0)
}
要求:macOS 12.0+
import Foundation
public final class NetworkingClient: NSObject {
public let session: URLSession
private let collectMetrics: Bool
public init(configuration: URLSessionConfiguration = .ephemeral,
collectMetrics: Bool = true,
delegateQueue: OperationQueue? = nil) {
self.collectMetrics = collectMetrics
// 建议:根据业务设置 timeoutIntervalForRequest/resource
configuration.waitsForConnectivity = true
self.session = URLSession(configuration: configuration,
delegate: collectMetrics ? MetricsDelegate() : nil,
delegateQueue: delegateQueue)
super.init()
}
// 可取消的 async/await JSON 拉取
public func fetchJSON<T: Decodable>(
from url: URL,
timeout: TimeInterval? = nil,
retries: RetryPolicy = .default,
decoder: JSONDecoder = JSONDecoder()
) async throws -> T {
var request = URLRequest(url: url)
request.httpMethod = "GET"
if let timeout { request.timeoutInterval = timeout }
request.setValue("application/json", forHTTPHeaderField: "Accept")
var attempt = 0
while true {
do {
let (data, response) = try await session.data(for: request)
try Task.checkCancellation()
guard let http = response as? HTTPURLResponse else {
throw NetworkError.invalidResponse
}
guard (200..<300).contains(http.statusCode) else {
throw NetworkError.httpStatus(http.statusCode, data)
}
do {
return try decoder.decode(T.self, from: data)
} catch {
throw NetworkError.decoding(error)
}
} catch {
if Task.isCancelled {
throw NetworkError.cancelled
}
// 超时与传输错误判定
if let urlError = error as? URLError {
if urlError.code == .timedOut { throw NetworkError.timeout }
// 仅对可重试错误与 5xx 场景进行退避重试(此处示例仅对传输错误重试)
if attempt < retries.maxAttempts {
attempt += 1
let jitter = Double.random(in: 0...(retries.baseDelay))
let delay = min(retries.baseDelay * pow(2, Double(attempt - 1)) + jitter, retries.maxDelay)
try? await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000))
continue
}
throw NetworkError.transport(urlError)
}
throw error
}
}
}
}
// 任务级网络指标收集(可选)
final class MetricsDelegate: NSObject, URLSessionTaskDelegate {
func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) {
// 将 metrics 上报到您的监控系统(如 DNS 时延、TLS 握手时间、协议版本等)
// 注意:避免记录敏感字段
}
// 可选:处理重定向
func urlSession(_ session: URLSession,
task: URLSessionTask,
willPerformHTTPRedirection response: HTTPURLResponse,
newRequest request: URLRequest,
completionHandler: @escaping (URLRequest?) -> Void) {
// 例如限制重定向次数、仅允许同源等策略
completionHandler(request)
}
// 可选:严格 TLS 校验/证书钉扎示例(按需启用)
/*
func urlSession(_ session: URLSession,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
// 默认 ATS 已启用。若需证书钉扎,使用 SecTrustEvaluateWithError 并比对公钥/证书指纹
completionHandler(.performDefaultHandling, nil)
}
*/
}
调用示例(可取消):
let client = NetworkingClient()
let task = Task {
struct Model: Decodable { let id: Int; let name: String }
return try await client.fetchJSON(from: URL(string: "https://example.com/data.json")!,
timeout: 10,
retries: .default) as Model
}
// 取消
// task.cancel()
要求:macOS 10.15+
import Combine
import Foundation
public func fetchJSONPublisher<T: Decodable>(
from url: URL,
timeout: TimeInterval? = nil,
session: URLSession = .shared,
decoder: JSONDecoder = JSONDecoder()
) -> AnyPublisher<T, NetworkError> {
var request = URLRequest(url: url)
request.httpMethod = "GET"
if let timeout { request.timeoutInterval = timeout }
request.setValue("application/json", forHTTPHeaderField: "Accept")
return session.dataTaskPublisher(for: request)
.tryMap { output -> Data in
guard let http = output.response as? HTTPURLResponse else {
throw NetworkError.invalidResponse
}
guard (200..<300).contains(http.statusCode) else {
throw NetworkError.httpStatus(http.statusCode, output.data)
}
return output.data
}
.decode(type: T.self, decoder: decoder)
.mapError { error in
if let net = error as? NetworkError { return net }
if let urlError = error as? URLError {
if urlError.code == .timedOut { return .timeout }
return .transport(urlError)
}
if error is DecodingError { return .decoding(error) }
return .transport(URLError(.unknown))
}
.eraseToAnyPublisher()
}
说明:
资产梳理
模型定义
接口替换
取消与生命周期
超时与重试
安全与合规
代理与重定向
指标与可观测性
错误模型统一
回归与灰度
以上方案在不牺牲安全与可维护性的前提下,提供更可靠的网络能力、可取消性与可观测性,符合苹果平台的现代 API 设计规范。
| 项 | 内容 |
|---|---|
| 函数名 | setFixedFrameRate(fps:) |
| 现有签名(Swift) | func setFixedFrameRate(fps: Int) |
| 目标平台 | watchOS |
| 主要用途 | 以固定帧率(如 30/60 fps)驱动心率图与运动轨迹的渲染 |
| 现有实现特性 | 依赖持续定时器与手动刷新,未与系统节能策略或屏幕刷新同步 |
| 已知问题 | 易耗电、在系统限频或 AOD 场景下易掉帧、不利于按需绘制与状态驱动更新 |
// MARK: - Deprecated
@available(*, deprecated, message: """
setFixedFrameRate(fps:) uses fixed-interval timers that are not display-synchronized \
and may increase power usage on watchOS. Migrate to SwiftUI TimelineView(.animation) \
or state-driven updates with withAnimation/Canvas for adaptive, on-demand rendering.
""")
public func setFixedFrameRate(fps: Int) { /* no-op or forward to adaptive path */ }
// Header (.h)
// MARK: - Deprecated
- (void)setFixedFrameRateWithFPS:(NSInteger)fps
__attribute__((deprecated("Use SwiftUI TimelineView-driven or state-driven adaptive rendering instead of fixed frame rates on watchOS.")));
说明:
技术原因:
业务背景:
总体策略:
适用:watchOS 8+(TimelineView/Canvas 为 SwiftUI 能力)
核心要点:
示例(简化示例,关注结构与时序,而非具体绘制细节):
import SwiftUI
// 数据模型(示意)
final class WorkoutRenderModel: ObservableObject {
struct HRPoint { let t: TimeInterval; let bpm: Double }
struct RoutePoint { let x: CGFloat; let y: CGFloat }
@Published var hrSeries: [HRPoint] = []
@Published var route: [RoutePoint] = []
// 外部数据到达时调用
func appendHeartRate(_ point: HRPoint) {
withAnimation(.easeInOut(duration: 0.2)) {
hrSeries.append(point)
}
}
func appendRoutePoint(_ p: RoutePoint) {
withAnimation(.linear(duration: 0.15)) {
route.append(p)
}
}
}
struct WorkoutRenderView: View {
@StateObject private var model = WorkoutRenderModel()
var body: some View {
// 当需要时间推进的动画(如游标/渐隐)时使用 .animation 时间线
TimelineView(.animation) { timeline in
Canvas { context, size in
// 1) 轨迹绘制(示意)
if !model.route.isEmpty {
var routePath = Path()
if let first = model.route.first {
routePath.move(to: CGPoint(x: first.x, y: first.y))
for p in model.route.dropFirst() {
routePath.addLine(to: CGPoint(x: p.x, y: p.y))
}
}
context.stroke(routePath, with: .color(.green), lineWidth: 2)
}
// 2) 心率曲线(示意)
if !model.hrSeries.isEmpty {
var hrPath = Path()
// 将时间/数值映射到画布坐标(略)
// ...
context.stroke(hrPath, with: .color(.red), lineWidth: 1.5)
}
// 3) 可选的时间推进效果(基于 timeline.date)
// 例如:根据 timeline.date 控制光标位置/尾迹衰减
}
}
// 数据输入示意(真实项目中改为 HealthKit/定位更新的 publisher)
.task {
// 示例:模拟数据注入,真实实现请替换为数据流
for i in 0..<100 {
try? await Task.sleep(nanoseconds: 200_000_000) // 200ms
model.appendHeartRate(.init(t: CFAbsoluteTimeGetCurrent(), bpm: 60 + Double(i % 40)))
}
}
}
}
说明:
适用:已有 Objective‑C WatchKit 界面,但希望采用 SwiftUI 的按需绘制
步骤要点:
桥接示例(骨架):
// Swift
@objc public final class AdaptiveRenderController: NSObject {
@objc public static let shared = AdaptiveRenderController()
private let model = WorkoutRenderModel()
@objc public func appendHeartRateSample(time: TimeInterval, bpm: double_t) {
model.appendHeartRate(.init(t: time, bpm: bpm))
}
@objc public func hostingController() -> WKHostingController<WorkoutRenderView> {
return WKHostingController(rootView: WorkoutRenderView())
}
}
// Objective-C(使用示意)
// 在需要展示时 push SwiftUI 宿主
// [self pushControllerWithName:@"Hosting" context:[AdaptiveRenderController shared]];
// 或者在 Storyboard/代码中直接使用 hostingController
适用:无法引入 SwiftUI 时
骨架示例(仅结构):
// Objective-C
@interface HeartRouteScene : SKScene
@end
@implementation HeartRouteScene
- (void)update:(NSTimeInterval)currentTime {
// 依据数据变化更新节点属性(路径、位置、alpha 等)
// 避免固定频率 Timer,使用场景自带的更新回调
}
@end
示例条件编译(Swift):
if #available(watchOS 8.0, *) {
// TimelineView / Canvas 路径
} else {
// SpriteKit 或谨慎使用 Timer(设置 tolerance,且在不可见时停止)
}
以上方案遵循 watchOS/SwiftUI 的按需绘制和自适应刷新原则,避免固定帧率带来的功耗与稳定性问题,并提供 Swift 与 Objective‑C 环境下的可落地迁移路径。
面向iOS开发者与团队,快速产出“可直接落地”的函数弃用说明与迁移方案,做到标准统一、表达清晰、输出即用。通过一次输入函数名与功能描述,自动生成包含版本标记、替代建议、迁移步骤、兼容性说明,以及Swift/Objective‑C两套警告代码的完整内容,帮助你在框架升级、API重构、功能替换时高效推进;减少重复沟通与返工,降低上架与维护风险,加速版本发布与代码评审通过。
在提交合并前快速生成规范弃用警告与替代示例,缩短写文档时间,降低因表述不清造成的代码评审阻塞。
制定统一弃用策略与模板,批量指导团队迁移路径,把控版本兼容风险,沉淀团队标准与最佳实践。
依据兼容性说明与迁移步骤设计用例,明确各系统版本的验收要点,提前发现回归风险。
将模板生成的提示词复制粘贴到您常用的 Chat 应用(如 ChatGPT、Claude 等),即可直接对话使用,无需额外开发。适合个人快速体验和轻量使用场景。
把提示词模板转化为 API,您的程序可任意修改模板参数,通过接口直接调用,轻松实现自动化与批量处理。适合开发者集成与业务系统嵌入。
在 MCP client 中配置对应的 server 地址,让您的 AI 应用自动调用提示词模板。适合高级用户和团队协作,让提示词在不同 AI 工具间无缝衔接。
半价获取高级提示词-优惠即将到期