UITableView委托的问题

时间:2011-07-14 17:30:41

标签: iphone objective-c cocoa-touch uitableview nsstring

我正在合成一些字符串:

·H

@property(nonatomic,copy) NSString* bio;

的.m

@synthesize       bio;

//connectionDidFinish method
bio = [[[profile objectForKey:@"user"] valueForKey:@"profile"] valueForKey:@"bio"];

当我的tableview首次加载时,我在cellForRowAtIndexPath中收到错误-[NSNull length]: unrecognized selector sent to instance 0x11d45e8

case kBioSectionDescriptionRow:                 
                    if ([bio length]==0 ||bio == nil) {
                        cell.textLabel.text = @"bio";   
                        cell.selectionStyle = UITableViewCellSelectionStyleNone;
                        cell.detailTextLabel.numberOfLines = 5;
                        cell.detailTextLabel.font = [UIFont fontWithName:@"Helvetica Neue" size:(14.0)];
                        cell.detailTextLabel.lineBreakMode = UILineBreakModeWordWrap;
                        cell.detailTextLabel.text = @"None"; 
                    }
                    else{
                        cell.textLabel.text = @"bio";   
                        cell.selectionStyle = UITableViewCellSelectionStyleNone;
                        cell.detailTextLabel.numberOfLines = 5;
                        cell.detailTextLabel.font = [UIFont fontWithName:@"Helvetica Neue" size:(14.0)];
                        cell.detailTextLabel.lineBreakMode = UILineBreakModeWordWrap;
                        cell.detailTextLabel.text = [NSString stringWithFormat: @"%@", bio]; 
                    }

                    break;

如何确保我的生物被分配而不是空?

2 个答案:

答案 0 :(得分:3)

如果您@synthesize属性为bio,为什么要使用变量代替属性?

而不是直接影响变量bio = [[[profile objectForKey:@"user"] valueForKey:@"profile"] valueForKey:@"bio"];,而是需要影响属性本身:self.bio = [[[profile objectForKey:@"user"] valueForKey:@"profile"] valueForKey:@"bio"];


更准确地说,编写self.bio = xx意味着它调用bio属性的setter方法。此setter将为您管理内存,这意味着它将释放bio属性的先前值并复制新值。

如果您改为编写bio = xx,从而直接影响实例变量而不是属性,则不会执行任何释放或复制,因此您不会保留或复制您对生物变量影响的对象并将在当前RunLoop的末尾销毁。

这就是你的代码崩溃的原因,因为你试图访问bio变量,它不再指向任何东西(实际上它指向垃圾,在你的因为真实对象已被破坏,所以它错误地认为是[NSNull null]对象的情况!


实际上,@synthesize bio只是要求编译器为属性'setter和getter生成代码,并且当您的属性使用nonatomic,copy属性定义时,生成的setter将如下所示:< / p>

-(void)setBio:(NSString*)value {
  if (value == bio) return; // if already the exact same object (same pointer), return

  [self willChangeValueForKey:@"bio"]; // For KVO
  [bio release]; // release previous value
  bio = [value copy]; // copy new value
  [self didChangeValueForKey:@"bio"]; // For KVO
}

注意:不要忘记在dealloc方法中释放bio变量(或将self.bio属性设置为nil)以避免内存泄漏

答案 1 :(得分:0)

你对bio in -connectionDidFinish的转让应该是对self.bio的转让。