ios - 将 struct 转换为 Objective-C 数组或类

标签 ios objective-c iphone c struct

我是 IOS 新手。我有一些 OS X 和 java 的源代码。我正在尝试转换成IOS。 在 OS X 中,我有以下内容。

struct _NoteData {
    int number;             /** The Midi note number, used to determine the color */
    WhiteNote *whitenote;   /** The white note location to draw */
    NoteDuration duration;  /** The duration of the note */
    BOOL leftside;          /** Whether to draw note to the left or right of the stem */
    int accid;              /** Used to create the AccidSymbols for the chord */
};
typedef struct _NoteData NoteData;

@interface ChordSymbol : NSObject <MusicSymbol> {

    _NoteData notedata[20];/** The notes to draw */

}

_NoteData 这里就像一个数组和类。 numberwhitenoteduration..是_noteData的实例变量。

我试图将结构更改为 objective-c 类:

@interface  _NoteData:NSObject{
    @property NSInteger number_color;       
   @property WhiteNote *whitenote;   
   @property NoteDuration duration;  
   @property BOOL leftside;          
   @property NSInteger accid;    
  };
    @interface ChordSymbol : NSObject <MusicSymbol> {

    _NoteData notedata[20];/** The notes to draw */

}

在我的 .m 文件中,它有

+(BOOL)notesOverlap:(_NoteData*)notedata withStart:(int)start andEnd:(int)end {
    for (int i = start; i < end; i++) {

        if (!notedata[i].leftside) {
           return YES;
       }
   }
return NO;
}

!notedata[i] 抛出错误读取数组元素的预期方法。我知道 _NoteData 是一个类,而不是一个数组。我应该改变什么?

在java中:

 private NoteData[] notedata;

NoteData 是一个类,notedata 是一个存储 NoteData 的数组。 java 中的方法相同

 private static boolean NotesOverlap(NoteData[] notedata, int start, int end) {
    for (int i = start; i < end; i++) {
        if (!notedata[i].leftside) {
            return true;
        }
    }
    return false;
}

我觉得我需要的只是用 _NoteData 对象声明一个数组。我怎样才能做到这一点?

最佳答案

Objective-C 是 C 的超集,因此您可以在 Objective-C 代码中使用 C 结构体。您可以将代码保留在第一段中。您需要移动 ChordSymbol 类的头文件中的函数声明。

+(BOOL)notesOverlap:(NoteData*)notedata withStart:(int)start andEnd:(int)end;

在另一个 Objective-C 类的实现文件中,像这样调用 Class 函数。

NoteData y[] = {
    { .leftside = YES },
    { .leftside = YES },
    { .leftside = YES },
    { .leftside = YES }
};

BOOL result = [ChordSymbol notesOverlap:y withStart:0 andEnd:3];
NSLog(@"%d",result);

编辑

您可以使用NSArray来实现此目的。您创建一个数组并使用 NoteData 对象填充其数据。

NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:20];
NoteData *data1 = [[NoteData alloc] init];
data1.number_color = 1;
[array addObject:data1];

然后您应该将 (_NoteData*)notedata 更改为 (NSArray*)array,它应该可以工作。

关于ios - 将 struct 转换为 Objective-C 数组或类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26925761/

相关文章:

ios - 直接设置 bool 值会更快,还是不会节省任何时间?

objective-c - 向 NSView 添加 subview 会显示,但无法删除

iphone - 如何为 alpha 蒙版图像创建位图上下文?

ios - 如何在十位数字后关闭数字键盘?

ios - 如何在 iPad 上的 ios8 中呈现 UIPopoverController

objective-c - 自定义 Mac 安装程序覆盖/库/应用程序支持文件

ios - 如何从 Struct Swift 中显示一个字符串

ios - Xcode 中的信号中止 (SIGABRT) 异常

ios - iOS/Objective-C 中的 TCP 客户端 - 检查开放端口

iphone - UIToolbar 内的 UISegmentedControl 的横向高度确实错误