同一Workspace中跨不同Xcode Project访问类是否可行?
Can You Access Classes Across Different Xcode Projects in a Single Workspace?
Absolutely—you can access classes between separate Xcode projects in the same workspace, but it doesn’t happen automatically. You’ll need to set up proper dependencies and adjust access controls to make it work. Let me break this down clearly:
Core Requirements
First, understand that each project in your workspace acts as its own separate build target (unless configured to interact). To cross-access classes, you need to:
- Establish a build dependency between the projects
- Ensure the classes you want to access are marked as accessible to external targets
- Import the target/headers correctly in the consuming project
Step-by-Step Setup
1. Add Build Dependencies
Open your workspace, then select the project that needs to access the other project’s classes (let’s call this the "consumer" project):
- Go to the Build Phases tab of its target
- Under Target Dependencies, click the
+button and select the other project’s target (the "provider" project) - Next, under Link Binary With Libraries, add the provider target’s product (e.g., a
.frameworkor.afile) if it’s not already added
2. Make Classes Accessible
- For Swift: By default, classes are
internal(only accessible within their own target). Change the class declaration topublic(oropenif you need subclassing outside the target):public class ProviderClass { public func doSomething() { // Code here } } - For Objective-C: Move the header file of the class you want to share to the Public Headers section in the provider target’s Build Phases > Headers. Alternatively, ensure the consumer project can import the header via the provider’s module.
3. Import the Provider Target
- Swift: In the consumer project’s files, import the provider target by name (this matches the target name, not the project name):
import ProviderTargetName - Objective-C: Use module syntax to import the provider’s header:
#import <ProviderTargetName/ProviderClass.h>
Key Notes to Avoid Issues
- No Circular Dependencies: Don’t set up mutual dependencies (consumer depends on provider, and provider depends on consumer)—this will cause compile errors.
- Dynamic vs Static Libraries: If using a dynamic framework, ensure you embed it in the consumer target’s General > Frameworks, Libraries, and Embedded Content (set to "Embed & Sign" or "Embed Without Signing" as needed).
- Target Names: Double-check that you’re using the target name (not the project name) when importing—this is a common gotcha.
内容的提问来源于stack exchange,提问作者makkuzu
相关产品推荐
相关产品推荐

