1

Is it possible a structure as a class member in objective C? If yes how can I assign values to that structure from another class?

Anthony Cramp
  • 4,495
  • 6
  • 26
  • 27
diana
  • 427
  • 2
  • 10
  • 22

3 Answers3

5

Yes, you can. You either just expose the structure as a property (in which case you have to set/get the whole thing) or you write custom accessors that walk into the fields of the strucutre.

For a concrete example, CGRect is a structure (though it is hidden by a typdef), which means the frame property of UIView get and set a structure.

In other words:

CGRect myFrame = CGRectMake(0,0,320,480); //CGRect is a struct
myView.frame = myFrmae; //Setting a struct
Louis Gerbarg
  • 43,356
  • 8
  • 80
  • 90
1

You just use dot notation to assign and access the values. You can also use -> if you have a pointer to a struct.

typedef struct {
  int a;
  double b;
} SomeType;

// Define some class which uses SomeType
SomeType myVar;

myVar.a = 1;
myVar.b = 1.0;

SomeType* myPtr = &myVar;

NSLog (@"%i", myPtr->a);

// This works...
SomeType mySecondVar = myVar;

// But you have to be careful in cases where you have pointers rather than values.
// So this wouldn't work if either element was a C string or an array.
Stephen Darlington
  • 51,577
  • 12
  • 107
  • 152
0

Yes and there is an easy way to access that struct using Objective-C 2.0 Properties. Consider the following struct from Stephens post.

typedef struct {
  int a;
  double b;
} SomeType;

In your .h file you would declare the member in your @interface

@interface AClass : NSObject{
  SomeType member;
}

@property SomeType member;
@end

Remember that if you choose to go with pointers here you will need to manage your own memory.

And in your @implementation (your .m file) don't forget add a @synthesize

@implementation AClass
@synthesize member;
@end

I hope this helps.

Randaltor
  • 127
  • 1
  • 5
  • `assign` is the default behavior of synthesized properties, and the runtime is smart enough to know not to retain a struct. It can easily look at its type encoding and see that it's not an Objective-C object. – Dave DeLong Nov 06 '09 at 16:31