views:

336

answers:

2

Hi All,

I want to change the variable value which is a member of a structure of another class. But the value is not getting changed.

Here is the code.

//Structure..

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


//Class which has the structure as member..
@interface Test2 : NSObject {
    // Define some class which uses SomeType
    SomeType member;

}

@property SomeType member;

@end


@implementation Test2

@synthesize member;

@end


//Tester file, here value is changed..
@implementation TesstAppDelegate

@synthesize window;

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    // Insert code here to initialize your application 

    Test2 *t = [[Test2 alloc]init];

    t.member.a = 10;
//After this the value still shows 0

}

@end

I tried out with the below link.

http://stackoverflow.com/questions/1687144/structure-as-a-class-member-in-objective-c

Regards, Dhana.

A: 

Try using the traditional brackets rather than dot syntax:

[t member].a = 10;

and make sure you're checking the value correctly:

NSLog(@"%i",[t member].a);
andyvn22
+3  A: 

To make a change to your 'member' instance variable, you need to set it in its entirety. You should do something like:

SomeType mem = t.member;
mem.a = 10;
t.member = mem;

The problem is that t.member is being used as a "getter" (since it's not immediately followed by an '='), so t.member.a = 10; is the same as [t member].a = 10;

That won't accomplish anything, because [t member] returns a struct, which is an "r-value", ie. a value that's only valid for use on the right-hand side of an assignment. It has a value, but it's meaningless to try to change that value.

Basically, t.member is returning a copy of your 'member' struct. You're then immediately modifying that copy, and at the end of the method that copy is discarded.

sb
Oh, `t.member.a` is just fine for _reading_ the value of `member.a`. It's exactly the same as `[t member].a`.
sb
Yeah, it works fine..I was trying to do everything in one step..
Dhanaraj