【问题标题】:How to access properties of a .m file into another .m file?如何将 .m 文件的属性访问到另一个 .m 文件中?
【发布时间】:2014-01-30 04:25:58
【问题描述】:

我有类 ABCD.m,如下所示

**ABCD.m**
@property (nonatomic, strong) UIButton *button;
@property (nonatomic, strong) NSString *string;
- (void) firstMethod;
- (void) setTheButtonWithBool:(BOOL)var1 withString:(NSString *)var2;

-(void) firstMethod {
 // Alloc init button
 self.button.enabled = NO;
}

- (void) setTheButtonWithBool:(BOOL)var1 withString:(NSString *)var2  {
  self.button.enabled = var1;
  self.string = var2;
}

还有另一个类Test.m(XCTestCase的子类)来编写ABCD.m的单元测试用例

**Test.m** //Sub-class of XCTestCase

//Extension
@interface ABCD.m () 
 @property (nonatomic, strong) UIButton *button;
 @property (nonatomic, strong) NSString *string;
 - (void) firstMethod;
 - (void) setTheButtonWithBool:(BOOL)var1 withString:(NSString *)var2;
@end


@interace Test : XCTestCase

- (void)testSomeMethod {
 ABCD *abcd = [ABCD alloc] init];  
 BOOL *var1 = YES; 
 NSString *var2 = @"StackOverFlow";
 [abcd firstMethod]; 
 [abcd setTheButtonWithBool:var1 withString:var2];
 nslog(@"Result1 :%hhd", self.abcd.button.isEnabled);             -----
 nslog(@"Result2: %@", self.abcd.string);                         -----
 // Assert statement

}

输出:

结果 1:否

结果 2:堆栈溢出

当我设置属性“字符串”时,它被设置为“StackOverFlow”。但是对于 UIButton 属性“按钮”,它没有设置为“否”。 为什么我不能设置 UIButton 的“启用”属性,因为我可以从 Test.m 类设置 ABCD.m 的 NSString

【问题讨论】:

  • 首先请检查按钮对象是否已初始化。因为您的示例中没有用于初始化按钮的代码。

标签: ios objective-c uibutton objective-c-category xctest


【解决方案1】:

问题很简单。您永远不会在您的 ABCD 实例上设置 button 属性。没有代码可以创建 UIButton 并将其分配给 button 属性。

self.button.enabled = NO 这样的调用被转换为[[self button] setEnabled:NO]。由于您尚未设置button,因此对[self button] 的调用将返回nil。所以现在你在 nil 对象上调用 setEnabled:,这基本上是一个空操作。

添加代码以创建按钮并设置button 属性,其余代码将正常工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-09
    相关资源
    最近更新 更多