OGeek|极客世界-中国程序员成长平台

标题: ios - 下面的 NSObject 代码是多余的吗? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 11:32
标题: ios - 下面的 NSObject 代码是多余的吗?

我正在学习这里的教程:http://blog.soff.es/archiving-objective-c-objects-with-nscoding 创建一个可以在回合制游戏中保存我的比赛数据的 NSObject。

但是我在 .m 文件中收到此警告:

Autosynthesized property 'title' will use synthesized instance variable '_title', not existing instance variable 'title'

所以我的问题是如果(在下面的代码中)我删除括号之间的代码会丢失一些重要的东西吗?

 @interface Note : NSObject <NSCoding> {
  NSString *title;
  NSString *author;
  BOOL published; 
 }

 @property (nonatomic, copy) NSString *title;
 @property (nonatomic, copy) NSString *author;
 @property (nonatomic) BOOL published;

 @end



Best Answer-推荐答案


您不应该显式声明 ivars,因为属性会自动合成它们自己的 ivars,但名称略有不同。显式 ivars 没有意义,不会被属性使用。当您打算设置属性时错误地使用您的 ivars 时,拥有它们只会导致错误。

警告通过让您知道会有两个相似的 ivars 来指出这一点。

您的代码应该是:

 @interface Note : NSObject <NSCoding>

 @property (nonatomic, copy) NSString *title;
 @property (nonatomic, copy) NSString *author;
 @property (nonatomic) BOOL published;

 @end

这样可以避免以下错误:

title = @"Some Title"; // sets your ivar, not the property

相对于:

_title = @"Some Title"; // directly sets the property's ivar

当然你应该使用这个属性:

self.title = @"Some Title"; // uses the property methods

关于ios - 下面的 NSObject 代码是多余的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32080374/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4