1

下面是我的问题的简化示例。我正在尝试存储具有不同值的相同对象。但是当我设置一个新值时,所有值都会改变。

StopsOnRoute.h

@interface StopsOnRoutes : NSObject

@property (nonatomic) NSUInteger start_route_id;
@property (nonatomic) NSUInteger start_stop_id;
@property (nonatomic) NSUInteger start_time;

@end

第一视图控制器.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];
     }
}

数组 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

数组 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
4

1 回答 1

5

您一遍又一遍地重用同一个对象实例。每次在循环中创建一个新的。

 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];
 }
于 2013-11-11T20:27:53.187 回答