Reputation: 18511
Below is a simplified example of my problem. I am trying to store the same object with different values. But when I set a new value, all the values change.
StopsOnRoute.h
@interface StopsOnRoutes : NSObject
@property (nonatomic) NSUInteger start_route_id;
@property (nonatomic) NSUInteger start_stop_id;
@property (nonatomic) NSUInteger start_time;
@end
FirstViewController.m
- (void)viewDidLoad
{
NSMutableArray *route1 = [[NSMutableArray alloc] init];
StopsOnRoutes *stopOnRoutes = [[StopsOnRoutes alloc] init];
int p_time = 0;
int p_route = 0;
int p_stop = 0;
while(p_time<10){
p_time = p_time + 1;
p_route = p_route + 1;
p_stop = p_stop + 1;
[stopOnRoutes setStart_time:p_time];
[stopOnRoutes setStart_route_id:p_route];
[stopOnRoutes setStart_stop_id:p_stop];
[route1 addObject:stopOnRoutes];
}
}
Unexpected output of array route1:
10 | 10 | 10
10 | 10 | 10
10 | 10 | 10
10 | 10 | 10
10 | 10 | 10
10 | 10 | 10
10 | 10 | 10
10 | 10 | 10
10 | 10 | 10
10 | 10 | 10
Expected output of array route1:
1 | 1 | 1
2 | 2 | 2
3 | 3 | 3
4 | 4 | 4
5 | 5 | 5
6 | 6 | 6
7 | 7 | 7
8 | 8 | 8
9 | 9 | 9
10 | 10 | 10
Upvotes: 1
Views: 54
Reputation: 318824
You are reusing the same object instance over and over. Create a new one each time in the loop.
while(p_time<10){
StopsOnRoutes *stopOnRoutes = [[StopsOnRoutes alloc] init];
p_time = p_time + 1;
p_route = p_route + 1;
p_stop = p_stop + 1;
[stopOnRoutes setStart_time:p_time];
[stopOnRoutes setStart_route_id:p_route];
[stopOnRoutes setStart_stop_id:p_stop];
[route1 addObject:stopOnRoutes];
}
Upvotes: 5