tags:

views:

225

answers:

3

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?

+4  A: 

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
Can you explain a little detail. becoz i am new to C.
diana
+1  A: 

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
A: 

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
`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
Thanks, I'll make the edit.
Randaltor