Objective-C Address of property expression

有些话、适合烂在心里 提交于 2019-12-05 08:17:59

As the comments suggest, you cannot take the address of a property. A property is really just a promise that the object in question provides accessors for some value. The value itself may or may not even exist in an instance variable. For example, the getter for a property called fullName might generate the required value on the fly by concatenating the values of firstName and lastName properties.

Since you need to pass the address of a SDL_Rect into SDL_BlitSurface(), you could first copy the necessary property into a local variable, and then pass the address of that variable:

Rectangle *rect = [[Rectangle alloc] init];
SDL_Rect wall = rect.wall;
SDL_BlitSurface(camera, NULL, background, &wall);

If you need to preserve the value left in wall after the call to SDL_BlitSurface(), copy it back again after the call:

rect.wall = wall;
Elise van Looij

I had a similar situation with subclasses needing to access a CGAffineTransform defined in the parent class. The answer came from @orpheist's answer to this question: Get the address of an Objective-c property (which is a C struct). It does involve adding a method to your Rectangle class.

@interface Rectangle : NSObject
{
    NSRect wall;
    NSRect ground;
}
@property NSRect wall;
@property NSRect ground;
@end

@implementation Rectangle
@synthesize wall = _wall; //x;
@synthesize ground = _ground; //y;

- (const NSRect *) addressOfWall {
    return &_wall;
}

- (const NSRect *) addressOfGround {
    return &_ground;
}

+(instancetype)standardRectangle
{
    Rectangle *newInstance = [[self alloc] init];
    newInstance.wall = NSMakeRect(0,0, 300, 100);
    newInstance.ground = NSMakeRect(0 ,0, 300, 450);
    return newInstance;
}
@end

Now you can use, for instance, addressOfWall thus:

- (void)testWall
{
    Rectangle *rect = [Rectangle standardRectangle];
    XCTAssertEqual(100, [rect addressOfWall]->size.height);
}
Walkertop

Address of property expression requested that means:

@preperty (nonatomic,copy) NSString *name;

if you want to get the address of self.name. You cannot write the code like this:

NSLog (@"%p",&(self.name));

Because in fact,self.name is getter method, like this:

- (NSString *)name {
    return _name;
}

so you cannot get address of method.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!