【问题标题】:Setting UILabel to Null value causing exception将 UILabel 设置为 Null 值导致异常
【发布时间】:2013-09-28 01:04:14
【问题描述】:

我正在尝试设置我的 UILabel 文本属性并获得异常 NSInvalidArgumentException 原因:'-[NSNull 长度]:无法识别的选择器已发送到实例 0x2591068

在进行一些调试后,我可以看到我要设置的值是 ,但我不明白为什么这是一个问题。这似乎与我的数据库结果与对象中如何返回 NULL 有关。这是背景。

////////

ContactsModel - 这是我的对象,由数据库中 NSArray 的结果填充。

#import "ContactModel.h"

@implementation ContactModel


@synthesize contactId;
@synthesize status;
@synthesize phone1;
@synthesize thumb_url;
@synthesize fullname;
@synthesize phone2;

- (id)init {
self = [super init];
if (self) {
    self.thumb_url = nil;
    self.status = nil;
    self.fullname = nil;
    self.phone1 = nil;
    self.phone2 = nil;
}
return self;
}

///////视图控制器

列表视图。 - 列表视图通过下面的 segue 将填充的对象传递给详细视图。

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if ([segue.identifier isEqualToString:@"pushContactDetail"])
{
    GlobalVars * sharedGlobalVars = [GlobalVars sharedGlobalVars];
    NSArray *indexPaths = [self.imageCollection indexPathsForSelectedItems];
    ContactDetail *detailView = (ContactDetail *) segue.destinationViewController;
    NSIndexPath *index = [indexPaths objectAtIndex:0];
    NSLog(@"%d", index.section * 2 + index.row);
    //TODO:  Figure out what the hell this means
    ContactModel *contact =[sharedGlobalVars.contactsContent objectAtIndex:index.section   * 2 + index.row];
    detailView.contact = contact;
}

Detail View - 在此方法中将对象分配给 UI

- (void) loadContent
{
ImageCache *imgCache = [ImageCache sharedImageCache];
//publisherPhone1.text = self.contact.phone1;
publisherPhone2.text = self.contact.phone2;   //THIS NOT WORKING IF NULL
publisherFullName.text = self.contact.fullname;
UIImage *image = [imgCache getCachedImage:self.contact.thumb_url];
publisherImage.image = image;

}

当我在这里输出对象的值是我得到的一个例子

The value of phone2: <null>

如果我将加载内容方法更改为设置 self.contact.phone2 = nil 以进行测试,一切都很好。这就是让我认为和 nil 之间存在差异和问题的原因。

感谢您提供的任何帮助

【问题讨论】:

  • 你能告诉我们ContactModel对象中所有属性的类型吗?他们是 NSString* 吗?
  • 某人将Nil(重新)定义为[NSNull null],这与nil 不同。 (Nil 应该根据 objc.h 定义为与 nil 基本相同——一个空指针。)不要在你的环境中使用 Nil 除非并且直到你弄清楚它是如何被搞砸的然后你解决这个问题。
  • 请注意,您可能会从某些接口获取 NSNull 对象,尤其是数据库和 JSON 接口。要测试 NSNull,请将指针值与[NSNull null]== 进行比较。 (因为[NSNull null] 是一个单例,所以== 比较就足够了。)
  • 所有 ContactModel 属性都是字符串。

标签: ios objective-c


【解决方案1】:

article 描述了 nil、Nil 和 NSNull 之间的区别。享受吧。

附:

self.contact.phone2 = nil;

我想会更好。

【讨论】:

  • 我更正了我上面的例子。我没有在我的代码中将 self.contact.phone2 设置为 nil。当我这样做时,一切正常。我要做的是确保在设置我的 text lable.text 值之前不必检查 nil 值。也许我可以在模型中处理?谢谢你的 cmets。
猜你喜欢
  • 1970-01-01
  • 2013-11-12
  • 1970-01-01
  • 1970-01-01
  • 2013-05-09
  • 1970-01-01
  • 2012-06-15
  • 1970-01-01
  • 2012-08-22
相关资源
最近更新 更多