为什么在项目中使用'assert'?(以及为何多次使用它)

Pau*_*aul 6 assert design-by-contract objective-c

我正在阅读示例代码ListAdder,并且在变量之后有很多断言,或者几乎在每个方法中使用,例如:

self.formatter = [[[NSNumberFormatter alloc] init] autorelease]; assert(self.formatter != nil);

要么 :

- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   #pragma unused(tv)
   #pragma unused(indexPath)
   UITableViewCell *    cell;

   assert(tv == self.tableView);
   assert(indexPath != NULL);
   assert(indexPath.section < kListAdderSectionIndexCount);
   assert(indexPath.row < ((indexPath.section == kListAdderSectionIndexNumbers) ? [self.numbers count] : 1));
Run Code Online (Sandbox Code Playgroud)

我在想,有什么意义呢?

谢谢

Pro*_*ica 5

它是契约式设计DbC的实施.

Objective C对DbC的前置条件,后置条件和不变量没有原生支持,但特别是后置和前置条件可以很好地实现宏.

以下是在Objective C中实现DbC的一些其他方法: