与指针和对象混淆(Objective-C) [英] Confusion with pointers and objects (Objective-C)

查看:62
本文介绍了与指针和对象混淆(Objective-C)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作者写道,每当point的值改变myRect's origin的值也会改变,但我不明白如何转origin 到一个对象修复它.创建对象和创建指针有什么区别?

The author wrote that whenever the value of point changes the value of myRect's origin will change as well, but I don't understand how turning origin into an object fixes it. What's the difference between creating an object and a pointer?

修正setOrigin方法:

-(void) setOrigin:(XYpoint *)pt {
    if (! origin)
        origin = [[XYpoint alloc] init];

    origin.x = pt.x;
    origin.y = pt.y;
}

<小时>

#import <Foundation/Foundation.h>

@interface XYPoint : NSObject 
@property int x, y;

@end

<小时>

#import "XYpoint.h"

@implementation XYPoint
@synthesize x, y;

@end

<小时>

#import <Foundation/Foundation.h>

@class XYPoint;
@interface Rectangle: NSObject

-(void) setOrigin: (XYPoint *) pt; 

@end

<小时>

#import "Rectangle.h"
#import "XYpoint.h"

@implementation Rectangle {
    XYPoint *origin;
}

-(void) setOrigin:(XYPoint *)pt {
    origin = pt;
}

@end

<小时>

#import "XYpoint.h"
#import "Rectangle.h"

int main (int argc, char *argv[]) {
    @autoreleasepool {
        Rectangle *myRect = [[Rectangle alloc] init];
        XYpoint *point = [[XYpoint alloc] init];

        point.x = 3;
        point.y = 8;

        [myRect setOrigin: point];
    }
    return 0;
}

推荐答案

XYPoint *origin; 是指向包含 xy<的对象的指针/代码>.特别是在这种情况下,您有两个指向同一个对象的引用.myRect.originpoint 指向同一个 XYpoint 对象.这意味着如果您通过任一方式更改 xy 的值(myRect.origin.x = 1point.x = 1),更新后的 xy 将在任何一种方式(myRect.origin).

XYPoint *origin; is a pointer to the object that contains x and y. In this case in particular you have two references that point to the same exact object. myRect.origin and point point to the same XYpoint object. What this means is if you change the value of x or y by either means (myRect.origin.x = 1 or point.x = 1), the updated x and y will be when accessed either way (myRect.origin or point).

这篇关于与指针和对象混淆(Objective-C)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆