开发者

Structure as a class member in Objective C

Is it possible a structure as a class member in objective C? If yes how can I assign values to t开发者_JS百科hat structure from another class?


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜