我是初學者ObectiveC用戶,請保留簡單的答案。我有相當多的C和C++經驗。ObjectiveC - 構造函數,內存管理
現在,使用ObjectiveC我想創建兩個對象,而不是使用屬性。我的問題是「這裏有什麼問題」,而不是「如何做不同」。 所以有我的代碼:
@implementation News
NSString *_title;
NSString *_excerpt;
NSString *_content;
NSString *_thumbnailURL;
NSString *_date;
-(id)initWithTitle:(NSString *)title excerpt:(NSString *)excerpt content:(NSString*)content thumbnail:(NSString *)thumbnailURL date:(NSString *)date {
self = [super init];
if (self) {
_title = [[NSString alloc] initWithString:title];
_excerpt = [[NSString alloc] initWithString:excerpt];
_content = [[NSString alloc] initWithString:content];
_thumbnailURL = [[NSString alloc] initWithString:thumbnailURL];
_date = [[NSString alloc] initWithString:date];
}
return self;
}
-(void)showData {
NSLog(@" title:%@", _title);
NSLog(@" excerpt:%@", _excerpt);
NSLog(@" thumbnailURL:%@", _thumbnailURL);
NSLog(@" date:%@", _date);
NSLog(@" getContent:%@", _content);
}
@end
現在我要創建兩個對象:
News *nws = [[News alloc] initWithTitle:@"title1" excerpt:@"excerpt1" content:@"content1" thumbnail:@"thumbnail1" date:@"date1"];
News *nws2 = [[News alloc] initWithTitle:@"title3" excerpt:@"excerpt3" content:@"content3" thumbnail:@"thumbnail3" date:@"date3"];
之後想展示什麼是這裏面的對象:
[nws showData];
[nws2 showData];
的結果是,兩個對象都有相同的值。全部以「3」結束。我認爲nws對象將包含以「1」結尾的值,nws2將包含具有「3」的值。但它不是那樣工作的。爲什麼?錯誤在哪裏? 請大家幫忙,謝謝!
問題是您在{@implementation中的字段周圍丟失{}。 – Jano
Jano,thx!原因是缺少{}字段。謝謝! – Sid
我正在考慮沒有{}的代碼是如何被編譯器解釋的。爲什麼編譯器沒有顯示任何警告......我不確定我是否可以理解潛在的答案(初學者Objective-C),但它確實很有趣。 – Sid