using
NSString * title;
NSString * detail;
outside of the @interface
part creates global variables. When you assign a variable to title
or detail
you don't set an instance variable of your object, you change those global variables. And since they are global, they are the same for all objects that reference them.
Turn those global variables into instance variables, or even better use @property
.
Your code is bad objective-c overall.
You should not use get
in getters that return variables. You should not have methods that start with init
and don't return self. You should only call init
in [[Foo alloc] init...]
situations. You should avoid unnamed parameters in your methods.
And there is no need to create strings from strings from strings.
Here is how I would write it:
// CustomObject.h
@interface CustomObject : NSObject
@property (copy, nonatomic) NSString * title;
@property (copy, nonatomic) NSString * detail;
- (id)initWithTitle:(NSString *)title detail:(NSString *)detail
@end
// CustomObject.m
#import "CustomObject.h"
@implementation CustomObject
- (id)initWithTitle:(NSString *)title detail:(NSString *)detail {
self = [super init];
if (self) {
// use stringWithString: to create @"" strings when title is nil
// if nil is a valid value for those variables you should use
// _title = [title copy];
_title = [NSString stringWithString:title];
_detail = [NSString stringWithString:detail];
}
return self;
}
@end
for (int i=0; i<10; i++) {
NSString *tempTitle = [NSString stringWithFormat:@"title %d",i];
NSString *tempDetail = [NSString stringWithFormat:@"detail %d",i];
CustomObject * myCustomObject = [[CustomObject alloc] initWithTitle:tempTitle detail:tempDetail];
[myMutableArray addObject:myCustomObject];
}
for (int i=0; i<10; i++) {
CustomObject *object = myMutableArray[i];
NSLog(@"%@", object.title);
// or NSLog(@"%@", [object title]); if you don't like dot-notation.
NSLog(@"%@", object.detail);
NSLog(@"----------------------------");
}