iOS   发布时间:2022-03-30  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了ios – getter和setter not working objective c大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我不能在目标c中这样做吗?

@interface Foo : NSObject {
     int apple;
     int banana;         
}

@property int fruitCount;
@end

@implementation Foo
@synthesize fruitCount; //without this compiler errors when trying to access fruitCount

-(int)getFruitCount {
      return apple + banana;
}

-(void)setFruitCount:(int)value {
      apple = value / 2;
      banana = value / 2;
}

@end

我正在使用这样的类:

Foo *foo = [[Foo alloc] init];
foo.fruitCount = 7;

然而,我的getter和setter没有被调用.如果我改为写:

@property (getter=getFruitCount,setter=setFruitCount:) int fruitCount;

我的getter被调用但是setter仍然没有被调用.我错过了什么?

解决方法

你的语法有点偏……
要在示例中为属性访问器定义自己的实现,请使用以下命令:

@implementation Foo
@dynamic fruitCount;

-(int)fruitCount {
   return apple + banana;
}
-(void)setFruitCount:(int)value {
      apple = value / 2;
      banana = value / 2;
}

@end

使用@synthesize告诉编译器创建认访问器,在这种情况下你显然不需要. @dynamic向编译器表明你将编写它们.以前在Apple的文档中有一个很好的例子,但它在4.0 SDK更新中以某种方式被破坏了…希望有所帮助!

大佬总结

以上是大佬教程为你收集整理的ios – getter和setter not working objective c全部内容,希望文章能够帮你解决ios – getter和setter not working objective c所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: