How do I create a C struct into a property of a class?
I have it:
typedef struct objTag{
float x;
float y;
BOOL isUP;
} object;
how to make an object such a property
@property (nonatomic, assign) object myObj;
and then...
@synthesize myObj = _myObj;
this compiles fine, but later in the code when I try something like
self.myObj.isUP = YES;
I get an "expression not assigned" message
source to share
It doesn't work because the compiler compiles this:
[[self getMyOj] setIsUP: YES];
You will notice that 'isUP' is a property on a C struct, not an Obj-C ivar object.
EDIT:
If you really want direct manipulation, you will need to do it like this.
typedef struct s {
int i;
} s;
@interface Test : NSObject {
s *myS;
}
@property (nonatomic, assign) s *myS;
@end
@implementation Test
@synthesize myS;
- (id) init {
self = [super init];
myS = malloc(sizeof(s));
myS->i = 0;
return self;
}
@end
// somewhere later.
Test *t = [[Test alloc] init];
t.myS->i = 10;
Note that you want to clear myS in the dealloc method.
source to share
This question goes back to the basics of programming C
(i.e. non-object oriented programming).
When you use a property that refers to a structure, you are grabbing a copy of that structure, not a reference to it.
If you write
CGRect rect = CGRectMake(...);
CGRect rect2 = rect;
You don't assign a rect2
link to rect
, you create a copy of the structure. Change rect2
doesn't change rect
.
Likewise, if you change the element of the structure returned as a property, you change the element of the copy of the rectangle that belongs to your object. There is literally NO good one that can arise from this - for this type of code is not used because you are changing the value of a struct element that is not referenced anywhere.
If you wanted to edit the structure that was actually used by the class, your property would have to return a pointer to it . It can be done, but the code gets messy, what is the cost:
typedef struct myObj{BOOL isUp;} TOBJECT;
...
@property (nonatomic, assign) TOBJECT* myObj; //in class interface
...
self.myObj = malloc(sizeof(TOBJECT)); //in init method.
...
self.myObj->isUp = YES; //elsewhere, even potentially outside the class.
...
free(self.myObj); //in class dealloc method.
source to share
This is similar to working with frames on UIViews - you need to assign the entire structure in one shot, not its values. So something like:
object obj = self.myObj;
obj.isUP = YES;
self.myObj = obj;
If you don't like that (it sucks!) Then don't use structs. Create a class with multiple properties on it. structs do exist because obj-c is a superset of c, you should avoid them if you can. :)
source to share