【问题标题】:Trouble Accessing Custom-Object Property in NSMutableArray在 NSMutableArray 中访问自定义对象属性时遇到问题
【发布时间】:2013-03-28 02:15:57
【问题描述】:

我在这里遇到了某种结构问题,因为我不确定我正在尝试做的事情是否可行:

我有三个自定义类,它们代表从机器代码转换而来的指令类型。每个类都具有指令功能和操作数等属性。它们在第三个 VC 中被初始化并转换为实例并放入 NSMutableArray,我成功地将 NSMutableArray 移动到第四个 VC。现在,我需要遍历数组的每个对象(不知道它是哪种类型的类)并访问它的“指令”属性(即 NSString)。这可能吗?

其中一个类的声明示例:

@interface iInstruction : NSObject

@property (strong) NSString *opCode;
@property (strong) NSString *rs;
@property (strong) NSString *rt;
@property (strong) NSString *immediate;
@property (strong) NSMutableString *instruction;

- (id) initWithBinary: (NSString *) binaryInstruction;

如何创建实例并将其移至第四个 VC:

iInstruction *NewI = [[iInstruction alloc] initWithBinary:binary32Bits];
[TranslatedCode appendFormat:@"%@\n", NewI.instruction];
[instructions addObject: NewI];

disassembledCode.text = TranslatedCode;
FourthViewController *theVCMover = [self.tabBarController.viewControllers objectAtIndex:3];
theVCMover.instructionsInfo = instructions;

我正在尝试做的事情失败了:

for (NSUInteger i=0; i < [instructionsInfo count]; i++) {   //instructionsInfo is a property of the fourth VC that I use to move the main array from the third VC
    NSString *function = [instructionsInfo objectAtIndex:i].instruction;  //Of course it says property not found because it only receives the NSMutableArray at runtime

    if (function isEqualToString:@"andi") {
    }

【问题讨论】:

  • 嗨 James,您可能会发现 this 很有帮助,因为如果您应用它会简化与其他 Objective-C 开发人员的沟通,更多的人会愿意阅读您的代码以获得帮助。祝你好运!

标签: ios objective-c nsmutablearray


【解决方案1】:

试试这个:

for (iInstruction *instruction in self.instructionsInfo) {
    NSString *function = instruction.instruction;

    // and the rest
}

或者,如果您需要循环计数器:

for (NSUInteger i = 0; i < self.instructionsInfo.count; i++) {
    iInstruction *instruction = self.instructionInfo[i];
    NSString *function = instruction.instruction;

    // and the rest
}

编辑:由于数组似乎可以有不同的对象,但它们都具有instruction 属性,您可以这样做:

for (id obj in self.instructionsInfo) {
    NSString *function = [obj valueForKey:@"instruction"]; // use key-value coding

    // and the rest
}

【讨论】:

  • 这就是问题所在,它不一定属于 iInstruction 类……它可能属于其他两个类。但是,这三个都具有作为 NSString 的“指令”属性。
  • 查看我添加到答案中的更新。键值编码是解决这个问题的好方法。
  • 虽然是个好主意,但它给出了两个错误:“指向没有明确所有权的非常量类型 'id' 的指针”和“错误的接收器类型 '__strong id *”
  • 糟糕 - 去掉 for 循环中的星号。查看我的更新。
  • 太棒了!!!你,我的朋友,是一位编程艺术家!我以为我必须完全重构我的代码,唷。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-07
  • 2011-06-10
  • 1970-01-01
  • 1970-01-01
  • 2021-05-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多