Cocoa Objective-c Property 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
我尝试使用以下链接.
问候,达纳.
推荐答案
要更改成员"实例变量,您需要对其进行整体设置.您应该执行以下操作:
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;
那不会完成任何事情,因为 [t member]
返回一个结构体,它是一个r-value",即.一个仅适用于赋值右侧的值.它有一个价值,但试图改变那个价值是没有意义的.
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
正在返回您的成员"结构的副本.然后您立即修改该副本,并在该方法结束时丢弃该副本.
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 Property C 结构赋值失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!