I have a couple strings that I’m synthesizing:
.h
@property(nonatomic,copy) NSString* bio;
.m
@synthesize bio;
//connectionDidFinish method
bio = [[[profile objectForKey:@"user"] valueForKey:@"profile"] valueForKey:@"bio"];
When my tableview first loads I get an error -[NSNull length]: unrecognized selector sent to instance 0x11d45e8 in cellForRowAtIndexPath:
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;
How can I make sure that my bio is allocated and not null?
If you
@synthesizeyourbioproperty, why do you use the variable instead of the property?Instead of affecting the variable
bio = [[[profile objectForKey:@"user"] valueForKey:@"profile"] valueForKey:@"bio"];directly, you need instead to affect the property itself:self.bio = [[[profile objectForKey:@"user"] valueForKey:@"profile"] valueForKey:@"bio"];.To be more precise, writing
self.bio = xxmeans that it calls the setter method of the bio property. This setter will manage the memory for you, meaning it will release the previous value of the bio property and copy the new value.If you write
bio = xxinstead, thus directly affecting the instance variable and not the property, no release or copy is done, so the objet you affect to the bio variable is not retained nor copied and will be destroyed at the end of the current RunLoop.This is why your code crash, because you then try to access the
biovariable, which does not point to anything anymore (actually it points to garbage, in your case to sthg it erroneously believes to be the[NSNull null]object) as the real object has been destroyed since!Actually,
@synthesize biojust asks the compiler to generate the code for the property’ setter and getter, and as your property is defined with thenonatomic,copyattributes, the generated setter will look like this:Note: Don’t forget to release the bio variable in your
deallocmethod (or to set theself.bioproperty tonil) to avoid leaking memory