Cocoa Objective-c Property C structure assign fail

2019-01-17 13:08发布

问题:

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.

回答1:

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.



回答2:

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;



回答3:

Change the synthesize line to:

@synthesize member = _member;

Then you can assign values in one line of code:

_member.a = 10;