Reputation: 85
I'm beginner ObectiveC user so please keep potential answers simple. I have quite a few years experience with C and C++.
Now, with ObjectiveC I want to create two objects, not using properties. My question is "what is wrong here" not "how to do it differently". So there is my code:
@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
Now I want to create two objects:
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"];
After that want to show whats is inside this objects:
[nws showData];
[nws2 showData];
Result is that both objects have the same values inside. All ended with "3". I thought that nws object will containt values ending with "1" and nws2 will contain values with "3". But it isnt working like that. Why? Where is an error? Please help and thanks!
Upvotes: 1
Views: 130
Reputation: 3606
Your variables are defined as global variables
(and not instance variables), this why they have the same same value referenced from your instances.
Embedding them in {} is a possible solution in your case.
Upvotes: 2
Reputation: 63667
I asked in twitter and got the following comment from @Bavarious:
https://gist.github.com/11c22c0edea5391a3799 (bold added)
Any variable declared outside of
@interface … {}
or@implementation … {}
is treated as a regular C variable. In your example,_excerpt
is a global (file scope) variable with static storage duration and could equivalently be placed at the top of the file before@interface
, or between@interface
and@implementation
, or between the implementation of two methods — it’s the same mechanism where file scope variables in C are defined outside of a function block.Variables with static storage duration can be used to realise class variables, a concept that doesn’t exist in Objective-C.
Upvotes: 2