【问题标题】:Create new class instance from within another instance method (Objective C)从另一个实例方法中创建新的类实例(目标 C)
【发布时间】:2011-12-17 17:09:16
【问题描述】:

我(基本上)是编程新手,并且正在尝试学习 Objective-C。我正在开发一个使用类的实例来存储和转换单位的单位转换程序。例如,如果我想将 1 英尺转换为英寸,程序会执行以下操作:

  1. 创建一个新的 Length 类实例 (myLength)
  2. 将值和单位存储在类的新实例 (myMass) 中
  3. 调用实例方法将值转换为新单位

我的 Length 类工作正常,正如我所期望的那样。

现在我想创建一个名为 Area 的新类,它创建 Length 类的两个实例,并使用 Length 类执行转换。但是,当我尝试从 Area.m 中声明 Length 类的新实例时,我收到警告“未声明长度”。

是否可以在实例方法中创建不同类的实例?更具体地说,我可以从 Area 类实例方法中创建我的 Length 类的两个实例吗?

(如果我有拙劣的术语,请提前原谅我)。

这是 Area.m 中给我带来麻烦的代码的 sn-p:

@implementation Area

-(void) setCompound: (double) myVal unit1: (char) c1 unit2: (char) c2

{

// Create two new instances of the Length class
// THE FOLLOWING TWO LINES ARE GIVING ME TROUBLE
Length * aLength = [[Length alloc] init];  
Length * bLength = [[Length alloc] init];

[aLength setLength:myVal units: c1]; // Set the value and units of first length

[bLength setLength: 1 units: c2]; // Set the value and units of the second length

}

@end

【问题讨论】:

    标签: objective-c class methods instance


    【解决方案1】:

    您需要在 Area.h 中导入您的 Length 头文件

    #import "Length.h"
    

    【讨论】:

    • 这个导入应该在Area.m,而不是Area.h。
    • 太棒了。早该想到的。非常感谢!
    • @Josh 我一直都是在header中导入头文件,然后在实现中导入对应的header...这是stanford iOS课程讲授的风格...(即import length. h 进入 area.h,将 area.h 导入 area.m)...这是错的吗?
    • @Josh 或者因为 Length 没有在任何方法签名中公开,所以没有必要按照我所说的方式进行操作?
    • 如果你需要在头文件中引用一个类,你应该使用forward declaration@class Length;让编译器知道这个名字。冒着自吹自擂的风险——你可以看看my recent answer about circular imports
    猜你喜欢
    • 2023-04-02
    • 2016-08-25
    • 1970-01-01
    • 2012-10-26
    • 1970-01-01
    • 2015-06-10
    • 1970-01-01
    • 2016-11-16
    • 2019-10-14
    相关资源
    最近更新 更多