Cocoa Objective-c属性C结构分配失败 [英] 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.
以下是代码。
//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
我试用了以下链接。
注意,
Dhana。
Regards, Dhana.
推荐答案
要对您的成员实例变量进行更改,需要对其进行完整设置。你应该这样做:
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;
问题是 t.member
作为一个getter(因为它没有紧跟一个'='),所以 t.member.a = 10;
是相同的 [t member] .a = 10;
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;
这不会完成任何事情,因为 ]
返回一个结构体,它是一个r值,即。该值仅在作业右侧使用有效。它有一个值,但尝试更改该值是没有意义的。
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.
基本上, t.member
你的'member'结构体的副本。然后,您立即修改该副本,并在方法结束时丢弃该副本。
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.
这篇关于Cocoa Objective-c属性C结构分配失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!