将struct转换为Objective c数组或类

时间:2014-11-14 08:26:25

标签: 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的实例变量。

我试图将struct更改为objective c class:

@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]抛出错误expected method to read array element。我理解_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对象的数组。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

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,它应该有效。

相关问题