正确的 .gitignore 配置

169 阅读2分钟
# Xcode 用户数据
**/xcuserdata/
*.xcodeproj/xcuserdata/
*.xcworkspace/xcuserdata/

# Xcode 构建文件
build/
DerivedData/

# CocoaPods - 只忽略 Pods 目录,不忽略 Podfile 和 Podfile.lock
Pods/

# macOS
.DS_Store

# 其他
*.swp
*~

提交代码时

git add Podfile Podfile.lock .gitignore
git commit -m "Update dependencies"
git push

执行 pod install 后,.xcodeproj 文件被修改了,产生了待提交的内容。

原因分析

当你运行 pod install 时,CocoaPods 会:

  1. ✅ 在 Pods/ 目录下载依赖库(已被 .gitignore 忽略)
  2. ⚠️ 修改 .xcodeproj/project.pbxproj 文件,添加对 Pods 的引用

首次克隆项目后

# 1. 克隆项目
git clone <your-repo-url>
cd 项目目录

# 2. 安装依赖
pod install

# 3. 提交 .xcodeproj 的修改(如果有)
git add eWordMedical.xcodeproj/project.pbxproj
git commit -m "Update project configuration after pod install"
git push

为什么会有这些修改? 可能的原因:

  1. 路径差异:不同电脑上的绝对路径不同
  2. CocoaPods 版本:不同版本的 CocoaPods 生成的配置略有差异
  3. 首次安装:如果项目之前没有正确提交 .xcodeproj

这样做的好处:

  • 保持项目文件与实际配置一致
  • 团队其他成员拉取后可以直接编译

预防措施 为了减少这种情况,团队应该 统一 CocoaPods 版本

# 查看当前版本
pod --version

# 在 Gemfile 中锁定版本(可选)
gem 'cocoapods', '~> 1.15'

确保 .xcworkspace 也被提交

# .xcworkspace 应该提交(包含工作区配置)
git add xxxx.xcworkspace

在 .gitignore 中只忽略用户数据

# 只忽略用户数据,不忽略项目文件
**/xcuserdata/
*.xcworkspace/xcuserdata/

⚠️ 可能冲突的情况

只有在以下情况会冲突:

  1. 同时修改项目结构

    • 你:添加了新文件 A
    • 同事:添加了新文件 B
    • 两个人都修改了 .xcodeproj
    • 结果:Git 合并冲突 ❌
  2. 同时更新依赖

    • 你:更新了 Alamofire 版本
    • 同事:更新了 SnapKit 版本
    • 两个人都修改了 Podfile.lock 和 .xcodeproj
    • 结果:需要手动合并 ⚠️

CocoaPods 库中的代码有报错问题每次我都需要手动修改为了防止每次都修改以下修改 使用 Podfile 的 post_install 钩子自动修复

post_install do |installer|
  installer.pods_project.targets.each do |target|
    if target.name == 'CountdownLabel'  # 替换为你的 Pod 名称
      target.build_configurations.each do |config|
        # 自动修复感叹号问题
        Dir.glob("Pods/CountdownLabel/**/*.swift").each do |file|
          contents = File.read(file)
          # 将 as !TimeZone 替换为 as? TimeZone
          new_contents = contents.gsub(/as !TimeZone/, 'as? TimeZone')
          File.write(file, new_contents) if contents != new_contents
        end
      end
    end
  end
end