PDA

View Full Version : Access elements of Test**




amalshah71
Jun 26, 2009, 08:24 AM
say for eg i have :

Test.h

@interface Test : NSObject
{
@public
NSString* temp;
}
-(id)init;
-(NSString*)giveMeRandomString;
@end


Test.m

@implementation Test

-(id)init
{
temp=@"temp";
return self;
}

-(NSString*)giveMeRandomString
{
return @"random";
}

@end


AnotherClass.m

@implementation AnotherClass

-(void)access
{
Test* t=[[Test alloc] init];

NSLog(t->temp); // ok

NSLog([t giveMeRandomString]); // ok

Test** tt=&t;

NSLog(tt->temp); // why such a access is permissible

NSLog(*tt->temp); // ok...should be this way and not like the above step

NSLog([tt giveMeRandomString]); // compiler error...alright

NSLog([*tt giveMeRandomString]); // ok
}

@end


So, why does < NSLog(tt->temp) > work?

Or is there something i am missing...


Thanks
amal



amalshah71
Jun 28, 2009, 11:01 PM
Guys...pls help....am not able to understand why such a behaviour is possible....in objective-c...or is it that there is something i am missing...

amal

kainjow
Jun 28, 2009, 11:18 PM
It doesn't work for me on Xcode 3.1.3. I get "error: request for member 'temp' in something not a structure or union"

amalshah71
Jun 29, 2009, 06:13 AM
It doesn't work for me on Xcode 3.1.3. I get "error: request for member 'temp' in something not a structure or union"

Sorry....i didn't include @property statement in Test file

Test.h

@interface Test : NSObject
{
@public
NSString* temp;
}
@property(nonatomic)NSString* temp;
-(id)init;
-(NSString*)giveMeRandomString;
@end


Test.m

@implementation Test

@synthesize temp;

-(id)init
{
temp=@"temp";
return self;
}

-(NSString*)giveMeRandomString
{
return @"random";
}

@end



amal

hazmatzak
Jun 29, 2009, 09:41 AM
If you consider that P->ivar is equivalent to (*P).ivar

because you declared a @property temp, which enables the dot operator

then your tt->temp is actually (*tt).temp

which does work, through property access. You can see this in a couple of ways. First, as you saw yourself, the code did not compile without declaring the property.

If you invoke the Xcode completion list with the cursor inside "temp" for t->temp, it tells you that the type is "Test" and that "temp" is a variable (with the "V" icon). If you do it in tt->temp, the type is "Test *" and "temp" is a property (with the "P" icon) -- the same as if you do it in t.temp.

Finally you can verify that the accessor is being called by defining one that returns something different than the instance variable.

Also, because of operator precedence, instead of *tt->temp, what you really mean is (*tt)->temp -- which accesses the public ivar.