创建可以在多个.h文件中使用的Core类

时间:2014-09-05 11:50:21

标签: ios objective-c xcode

我开始学习Xcode(Objective c)和im orginal c#/ vb程序员 面对以下问题,我无法找到合适的答案

当我创建像

这样的.h文件时
#import <UIKit/UIKit.h>

@interface Core : NSObject

@property BOOL *DebugMode;

@end

@implementation Core

-(void)SetDebugMode:(BOOL*)Debug
{
  self.DebugMode = Debug;
}

@end

如果我想在另外2个.h文件中使用该类(如UIViewController) 我通过

访问它
Core *cr = [[Core alloc]init];

它出现以下错误:

 Undefined symbols for architecture i386:
 "_OBJC_CLASS_$_Core", referenced from:
  objc-class-ref in AppDelegate.o
 ld: symbol(s) not found for architecture i386
 clang: error: linker command failed with exit code 1 (use -v to see invocation)

我也尝试在AppDelegate.m中使用它们 什么是目标c中的类和方法的正确使用 非常感谢你的提示和帮助。

我希望在.h UIViewcontroller代码或其他地方使用一个类 所以我可以使用像DebugMode等常规的东西。不知道如何在xcode中做到这一点

亲切的问候, 斯蒂芬。

2 个答案:

答案 0 :(得分:0)

您需要在界面上方#import您要使用它的文件顶部的头文件:

#împort "Core.h"

您的.h文件仅 公共API,它们不应包含实现。这就是你的.m文件的用途。换句话说,您的.h文件应如下所示:

#import <UIKit/UIKit.h>

@interface Core : NSObject

@property (nonatomic) BOOL DebugMode;

@end

并且您的.m文件(实现)应如下所示:

#import "Core.h"

@interface Core()

// Any private properties you want

@end

@implementation Core

-(void)setDebugMode:(BOOL)DebugMode
{
  _DebugMode = DebugMode;
}

@end

然后,当您准备好设置DebugMode时,在您要访问它的文件的顶部添加#import "Core.h",并将其设置为:

Core *co = [[Core alloc] init];
co.DebugMode = foo; // NOTE: You can access this @property (DebugMode) from a different class because it is in your public .h file.

注意:请勿在BOOL中使用星号:

-(void)SetDebugMode:(BOOL*)DebugMode // This is wrong.
-(void)setDebugMode:(BOOL)DebugMode // This is correct.

您还应该使用小写字母启动属性。

答案 1 :(得分:0)

你应该写

-(void)SetDebugMode:(BOOL*)Debug
{
  self.DebugMode = Debug;
}
在.m文件中

,并使你的.h文件看起来像这样

#import <UIKit/UIKit.h>

@interface Core : NSObject

@property BOOL *DebugMode;

@end

@implementation Core

-(void)SetDebugMode:(BOOL*)Debug; //only name

@end

之后你就可以像你一样打电话了

Core *cr = [[Core alloc]init];
[cr SetDebugMode:foo];
  • 在obj-c中你最好用小写字母开始方法名称以避免与类混淆:)
相关问题