2025-03-26 00:02:56 +08:00

43 lines
2.2 KiB
Markdown
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#ios
`#pragma mark` 是一个在 Objective-C 和 Swift 中用于在源代码中添加标记的预处理器指令(尽管在 Swift 中它实际上是通过 Xcode 的编辑器功能实现的,而不是语言本身的一部分)。这个指令或功能的主要目的是在 Xcode 的导航栏或者代码跳转菜单中创建一个可视化的分隔符或标签,以便开发者能够更快地找到和导航到代码中的特定部分。
### 使用方式
在 Objective-C 中,`#pragma mark` 指令后面通常跟着一个字符串,用于描述接下来的代码部分。例如:
``` objc
#pragma mark - Table View Data Source Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// ...
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// ...
}
```
在上面的例子中,`#pragma mark - Table View Data Source Methods` 创建了一个标记,使得在 Xcode 的导航栏中能够看到一个名为 “Table View Data Source Methods” 的分隔符,这有助于开发者快速定位到表视图数据源方法的实现。
### 在 Swift 中的使用
在 Swift 中,没有直接的 `#pragma mark` 指令。然而Xcode 提供了类似的功能,允许开发者通过添加特定的注释来创建标记。这通常是通过在方法或属性声明之前添加一行特殊的注释来实现的,如:
``` swift
// MARK: - Table View Data Source Methods
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// ...
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// ...
}
```
在这个例子中,`// MARK: - Table View Data Source Methods` 注释起到了与 Objective-C 中 `#pragma mark` 类似的作用,它在 Xcode 的导航栏中创建了一个名为 “Table View Data Source Methods” 的标记。
### 总结
`#pragma mark` 和 Swift 中的 `// MARK:` 注释都是用于在代码中添加可视化标记的工具,它们帮助开发者更快地导航和定位到代码中的特定部分。这些标记在大型项目中尤其有用,因为它们使得代码结构更加清晰,易于维护。