请看我的代码 1st。我正在尝试将一些 Car 对象添加到 MutableArray *parkPlace (该属性属于 Park 类)
我的预期结果应该如下所示:
CarParkSim[2662:303] Parking: Car Number:1 At:3 o'clok Position:0
CarParkSim[2662:303] Parking: Car Number:2 At:4 o'clok Position:1
CarParkSim[2662:303] Parking: Car Number:3 At:5 o'clok Position:2
但是,我得到的实际结果是这样的:
2012-12-22 12:13:46.085 CarParkSim[2662:303] Parking: Car Number:1 At:3 o'clok Position:0
2012-12-22 12:13:46.087 CarParkSim[2662:303] Parking: Car Number:2 At:4 o'clok Position:0
2012-12-22 12:13:46.088 CarParkSim[2662:303] Parking: Car Number:3 At:5 o'clok Position:0
我确实检查了 NSmutablearray,它是空的......它似乎将任何东西推入堆栈......有什么建议吗?谢谢
无论如何,这里是代码:公园类:
#import <Foundation/Foundation.h>
#import "Stack.h"
#import "Car.h"
@interface Park : NSObject
@property(strong,nonatomic)NSMutableArray *parkPlace;
@property(strong,nonatomic)Car *car;
-(void)carMoveIntoPark:(Car *)car;
@end
#import "Park.h"
@implementation Park
-(void)carMoveIntoPark:(Car *)car
{
if ([self.parkPlace count] <= 2) {
Car *car1 = [[Car alloc] init];
car1.carNumber = 1;
car1.timeIO = 3;
[self.parkPlace push:car1];
int carNumber = car.carNumber;
int carTimer = car.timeIO;
NSUInteger parkPosition = [self.parkPlace count];
NSLog(@"Parking: Car Number:%d At:%d o'clok Position:%ld", carNumber, carTimer, parkPosition);
} else {
//to be implement later
}
}
@end
这是我的主要内容:
int main(int argc, const char * argv[])
{
Car *car1 = [[Car alloc] init];
car1.carNumber = 1;
car1.timeIO = 3;
Car *car2 = [[Car alloc] init];
car2.carNumber = 2;
car2.timeIO = 4;
Car *car3 = [[Car alloc] init];
car3.carNumber = 3;
car3.timeIO = 5;
Park *park = [[Park alloc] init];
[park carMoveIntoPark:car1];
[park carMoveIntoPark:car2];
[park carMoveIntoPark:car3];
这是我的汽车课:
#import <Foundation/Foundation.h>
@interface Car : NSObject
@property(assign,nonatomic)int carNumber;
@property(assign,nonatomic)int timeIO;
@end
#import "Car.h"
@implementation Car
@end
顺便说一句,我正在尝试使用堆栈数据结构将汽车推到“堆栈”上,因为目标 c 中没有这样的数据结构,所以我实现了自己的,这里是堆栈类:
#import <Foundation/Foundation.h>
@interface NSMutableArray (Stack)
-(void) push:(id)item;
-(id)pop;
-(id)peek;
-(void)replaceTop:(id)item;
@end
#import "Stack.h"
@implementation NSMutableArray (Stack)
-(void)push: (id)item{
[self addObject:item];
}
-(id)pop {
id item = nil;
if ([self count] != 0) {
item = [self lastObject];
[self removeLastObject];
}
return item;
}
-(id)peek{
id item = nil;
if([self count] != 0) {
item= [self lastObject];
}
return item;
}
-(void) replaceTop:(id)item{
if([self count] == 0) {
[self addObject:item];
}else{
[self removeLastObject];
[self addObject:item];
}
}
@end