views:

54

answers:

1

Hi, i like to make an array out of an typedef struct i have.

It works fine when i work with a FIXED array size. But just to be open for bigger arrays i guess i have to make it with nsmutable array. But here i dont get it run

    //------------ test STRUCT
 typedef struct 
 {
  int id;
  NSString* picfile;
  NSString* mp3file;
  NSString* orgword;
  NSString* desword;
  NSString* category;
 } cstruct;

 //------- Test Fixed Array
 cstruct myArray[100]; 
 myArray[0].orgword = @"00000"; // write data
 myArray[1].orgword = @"11111";

 NSLog(@"Wert1: %@",myArray[1].orgword); // read data *works perfect



 //------ Test withNSMutable
 NSMutableArray *array = [NSMutableArray array];
    cstruct data;
    int i;
    for (i = 1;  i <= 5;  i++) {
  data.orgword = @"hallo";
  [array addObject:[NSValue value:&data withObjCType:@encode(struct cstruct)]];
 }

 data = [array objectAtIndex:2];  // something is wrong here
 NSLog(@"Wert2: %@",data.orgword); // dont work

any short demo that works would be appreciated :) still learning

Thx Chris

+5  A: 

It is highly unusual to mix structures containing Objective-C types with objects in Objective-C. While you can use NSValue to encapsulate the structure, doing so is fragile, difficult to maintain, and may not function correctly under GC.

Instead, a simple class is often a better choice:

 @interface MyDataRecord:NSObject 
 {
  int myRecordID; // don't use 'id' in Objective-C source
  NSString* picfile;
  NSString* mp3file;
  NSString* orgword;
  NSString* desword;
  NSString* category;
 }
 @property(nonatomic, copy) NSString *picfile;
 .... etc ....
 @end

 @implementation MyDataRecord
 @synthesize picfile, myRecordID, mp3file, orgword, desword, category;
 - (void) dealloc
 {
       self.picfile = nil;
       ... etc ....
       [super dealloc];
 }
 @end

This also makes it such that the moment you need to add business logic to said data record, you already have a convenient place to do so.

bbum