【问题标题】:getter and setter for int in objective c目标c中int的getter和setter
【发布时间】:2015-02-03 18:55:17
【问题描述】:

我是 Objective C 的新程序员...我的代码有一些问题,我不知道为什么会出错... 这是我的代码: 矩形.h:

    #import <Foundation/Foundation.h>



 @interface Rectangle : NSObject
    {
        int width;
        int height;
    }
        @property(setter=setWidthOfRect: , getter=getWidth) int width;
        @property(setter=setHeightOfRect: , getter=getHeight) int height;
 @end

矩形.m:

#import "Rectangle.h"

@implementation Rectangle
    @synthesize width, height;
    @end

这是 main.m:

#import <Foundation/Foundation.h>
#import "Rectangle.h"



int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Rectangle *rect = [[Rectangle alloc] init];
        [rect setWidthOfRect:22];
        [rect setHeightOfRect:28];
     NSLog(@"the area is: %d", [rect getHeight] * [rect getWidth]);

    }
    return 0;
}

我不明白:“区域是 616 有什么帮助吗?

【问题讨论】:

  • 我做到了,它给出了正确的答案。
  • 我认为你没有在看 LOG 或者它可能已关闭,这意味着你在看其他东西,而不是控制台。
  • 看起来没问题,除了上面代码中的一些复制粘贴,我正在编辑它。
  • 它突然起作用了!!我不知道为什么以前不起作用! ,谢谢@Duaan
  • 一个重要提示:Obj-C 在 getter 中不使用 get 前缀。

标签: ios objective-c iphone macos


【解决方案1】:

最好使用默认的getter/setter,只需像这样编写你的属性:

@property (nonatomic, assign) int width;

你甚至不需要写 @synthesize 和 ivars。比你可以这样使用它:

object.width = 5; // or
[object setWidth:5];

int width = object.width; // or
int width = [object width];

【讨论】:

  • 你为什么使用nonatomic?您是否非常关心性能,还是在这里覆盖 setter 或 getter?此外,您也不需要使用assign,因为它是非对象属性的默认值,这意味着@property int width; 绰绰有余。
  • 我使用atomic 仅当我知道此代码将在多个线程中使用时。在大多数情况下,它不是。 assign 怎么样,这只是我的代码风格偏好。代码在其他类型(weakstrong)的属性附近看起来更准确。 Apple 在他们的 SDK 标头中使用了相同的方法。
【解决方案2】:

摆脱属性宽度和高度之上的额外整数。属性使您已经指定的数据类型在其中您可以定义设置属性方法名称是什么,并获取属性名称以及其他属性标志。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-03
    • 2010-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-27
    • 2011-03-03
    相关资源
    最近更新 更多