【问题标题】:Objective-C Address of property expressionObjective-C 属性表达式的地址
【发布时间】:2014-12-14 10:56:19
【问题描述】:

我需要财产的访问地址,但有问题。示例代码是

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

@implementation Rectangle
@synthesize x;
@synthesize y;
@end

@interface Graphics : NSObject
{
    int w;
    int h;
}
-(void) drawSurface
@end

@implementation Graphics
-(void) drawSurface
{
    Rectangle *rect = [[Rectangle alloc] init];
    SDL_BlitSurface(camera, NULL, background, &rect.wall);
}
@end

&rect.x 是请求的属性表达式的地址

【问题讨论】:

  • 你不能,它是一个属性。
  • SDL_BlitSurface(camera, NULL, background, ); - 需要的最后一个参数是 CGRect,而不仅仅是 x 值。

标签: objective-c objective-c-runtime objective-c-2.0


【解决方案1】:

正如 cmets 所建议的,您不能获取房产的地址。属性实际上只是一个承诺,即所讨论的对象为某些值提供访问器。值本身可能存在也可能不存在于实例变量中。例如,名为fullName 的属性的getter 可能会通过连接firstNamelastName 属性的值来动态生成所需的值。

由于您需要将SDL_Rect 的地址传递给SDL_BlitSurface(),您可以先将必要的属性复制到局部变量中,然后传递该变量的地址:

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

如果您需要在调用SDL_BlitSurface() 后保留wall 中留下的值,请在调用后再次将其复制回来:

rect.wall = wall;

【讨论】:

    【解决方案2】:

    我遇到了类似的情况,子类需要访问父类中定义的 CGAffineTransform。答案来自@orpheist 对这个问题的回答:Get the address of an Objective-c property (which is a C struct)。它确实涉及向您的 Rectangle 类添加一个方法。

    @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
    

    现在你可以这样使用,例如,addressOfWall:

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

    【讨论】:

      【解决方案3】:

      请求的属性表达式的地址意味着:

      @preperty (nonatomic,copy) NSString *name;
      

      如果你想得到self.name的地址。你不能这样写代码:

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

      因为其实self.name是getter方法,像这样:

      - (NSString *)name {
          return _name;
      }
      

      所以你不能得到方法的地址。

      【讨论】:

      • 这是有道理的,但它不允许这样做仍然很奇怪,因为它在技术上是可计算的。我想知道是什么不明原因导致他们禁止这样做(假设有正当理由)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多