0

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

1
  • Your array is returning an instance of NSValue... that's what you put in there. So, to read: [[array objectAtIndex:2] getValue:&data]; Commented Jun 19, 2010 at 16:15

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.