Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cocoa Objective-c Property C structure assign fails

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.

Structure as a class member in Objective C

Regards, Dhana.

like image 491
Dhanaraj Avatar asked Mar 11 '10 13:03

Dhanaraj


2 Answers

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.

like image 182
sb. Avatar answered Oct 13 '22 00:10

sb.


Make a pointer to your struct instead, then just dereference it when you want to change a part of it.

Example:

struct myStruct {
    int a,
        b;
};

@interface myClass : NSObject {
myStruct *testStruct;
}

@property myStruct *testStruct;

Then to change a part of myStruct just do myClassObject.testStruct->a = 55;

like image 41
Dmacpro Avatar answered Oct 13 '22 01:10

Dmacpro