我工作的应用程序列出了一项运动的当前现场比赛。有关实时游戏的信息是使用REST从远程源获取的。第一个请求给出了他们的id和相应的竞技场ID的现场比赛列表。然后,我必须从他们的身份证获取竞技场名称。当所有完成后,我发回一个NSArray包含一个现场比赛列表。Objective-C NSArray,Block,STAssertEquals
在测试我的解析方法传递NSArray通过块时,我在SenTestCase中发现了一个奇怪的方法。在我的测试中,我能够执行[myArray count]
并将结果显示在NSLog中,但是当我使用EXC_BAD_ACCESS执行STAssertEquals([myArray count], 1, @"Error description")
测试崩溃时。
这是我的代码减少到最低限度,并且其中我删除所有的网络方面:
#import <SenTestingKit/SenTestingKit.h>
@interface LiveGameTests : SenTestCase
@end
@interface LiveGame : NSObject
@property (nonatomic) id gameID;
@property (strong, nonatomic) NSString *arenaName;
@end
@implementation LiveGame
// Create a live game object from a dictionary (this dictionary is the response of a first request to a remote server)
+(LiveGame *)gameWithData:(NSDictionary *)dict
{
LiveGame *liveGame = [[LiveGame alloc] init];
liveGame.gameID = dict[@"game_id"];
return liveGame;
}
// Complete a live game data with the element of a dictionary (those data are actualy fetched from a remote server in a different request.)
+(void)fetchRemainingData:(NSArray *)liveGameList completion:(void(^)(void))completion
{
LiveGame *liveGame = liveGameList[0];
liveGame.arenaName = @"arenaName";
completion();
}
// Parse a NSArray of NSDictionaries representing live game
+(void)parseArrayOfDictionary:(NSArray *)arrayToParse success:(void(^)(NSArray *liveGameList))success
{
NSMutableArray *liveGameList = [NSMutableArray arrayWithCapacity:[arrayToParse count]];
// Iterate on all the NSDictionary of the NSArray and create live game from each NSDictionary
[arrayToParse enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL *stop)
{
liveGameList[idx] = [LiveGame gameWithData:obj];
}];
[LiveGame fetchRemainingData:liveGameList completion:^
{
success(liveGameList);
}];
}
@end
@implementation LiveGameTests
-(void)testParseArrayOfDictionary
{
[LiveGame parseArrayOfDictionary: @[@{@"game_id": @1}]
success:^(NSArray *liveGameList)
{
// This line work fine and print: 2013-03-08 13:39:35.288 ShotClock[55177:c07] liveGameList count = 1
NSLog(@"liveGameList count = %d",[liveGameList count]);
// This crash the test on a EXC_BAD_ACCESS. What's wrong?
STAssertEquals([liveGameList count], 1, @"The list of game must contain one unique live game but contain %@",[liveGameList count]);
}];
}
@end
的NSLog(@ “liveGameList计数=%d”,[liveGameList计数]); =>此行可以正常工作并打印:2013-03-08 13:39:35.288 ShotClock [55177:c07] liveGameList count = 1
STAssertEquals([liveGameList count],1,@“游戏列表必须包含一个独特的现场比赛,但包含%@“,[liveGameList计数]); =>这会使EXC_BAD_ACCESS上的测试崩溃。怎么了?
感谢您的快速回答。这很明显,但我完全专注于NSArray和Block,因为之前的错误。 – JonathanGailliez 2013-03-08 13:26:23
非常自然!很容易忘记你的诊断可能是导致崩溃的原因! – 2013-03-08 13:35:46