我希望能够很好地理解它,但迄今为止我没有找到一个集中考虑所有可能性的复杂答案。我知道在现代的 Objective-C 中,我们不会在 @implementation Album
和 { }
之间创建 ivars。
只是为了测试,我创建了 Album.h:
@interface Album : NSObject
@property (nonatomic, copy, readonly) NSString *title, *artist;
@property (nonatomic, copy) NSString *title2, *artist2;
- (id)initWithTitle:(NSString*)title;
@end
在 Album.m 中:
@implementation Album
- (id)initWithTitle:(NSString*)title {
self = [super init];
if (self) {
//READ-ONLY
title = title; //1, still nil after compile
_title = title; //2,
self.title = title; //3, "assignment to readonly property"
self._title = title; //4, "property '_title' not found"
artist = @"Shakira"; //5, "use of undeclared identifier 'artist'"
_artist = @"Shakira"; //6
self.artist = @"Shakira"; //7, "assignment to readonly property"
self._artist = @"Shakira"; //8, "property '_artist' not found"
//READ-WRITE
title2 = title; //9, "use of undeclared identifier 'title2'"
_title2 = title; //10
self.title2 = title; //11
self._title2 = title; //12, "property '_title2' not found"
artist2 = @"Shakira"; //13, "use of undeclared identifier 'artist2'"
_artist2 = @"Shakira"; //14
self.artist2 = @"Shakira"; //15
self._artist2 = @"Shakira"; //16, "property '_artist2' not found"
}
return self;
}
@end
现在我正在使用它:
Album *album = [[Album alloc] initWithTitle:@"Live from Paris"];
问题如下:
- 为什么找不到4、8、12、16的属性,而2、6、10、14存在?
- 10和11或14和15有什么区别?
- 我在1中实际上做了什么?
- 我在哪里声明了2、6、10、14这些属性?
- 为什么我可以在2、6中分配只读属性,但不能在3、7中分配?
self.title = @"value"
,但是只读属性呢?当我输入self.title = @"value"
时,会出现错误。 - Bartłomiej Semańczyk