简体   繁体   中英

“unrecognized selector sent to instance” When setting a UILabel's text

I'm a student of iOS programming working through the Big Nerd Ranch book. I see that lots of other people have caught the same exception "unrecognized selector sent to instance" but can't find out what's causing it in my code.

It's happening in this method where I try to set the text of a UITableViewCell's UILabel.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    BNRItemCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BNRItemCell" forIndexPath:indexPath];
    NSArray *items = [[BNRItemStore sharedStore] allItems];
    //Set BNRItem instances to equal a given object in the items[] array
    BNRItem *item = items[indexPath.row];
    cell.nameLabel.text = item.itemName;  //This is the line where the exception happens
    cell.serialNumberLabel.text = item.serialNumber;
    cell.valueLabel.text = [NSString stringWithFormat:@"$%d", item.valueInDollars];
    cell.thumbnailView.image = item.thumbNail;

    return cell;

}

In the BNRItem implementation I'm using archiving to store the values of its properties (which are used to set the text in the text labels, which is where the exception gets thrown).

-(void) encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:self.itemName forKey:@"itemName"];
    [aCoder encodeObject:self.serialNumber forKey:@"serialNumber"];
    [aCoder encodeObject:self.dateCreated forKey:@"dateCreated"];
    [aCoder encodeObject:self.itemKey forKey:@"itemKey"];
    [aCoder encodeInt:self.valueInDollars forKey:@"valueInDollars"];
    [aCoder encodeObject:self.thumbNail forKey:@"thumbnail"];
}



- (instancetype) initWithCoder:(NSCoder *)aDecoder {
    self = [super init];
    if (self)
    {
        _itemName = [aDecoder decodeObjectForKey:@"itemName"];
        _serialNumber= [aDecoder decodeObjectForKey:@"serialNumber"];
        _dateCreated = [aDecoder decodeObjectForKey:@"dateCreated"];
        _itemKey = [aDecoder decodeObjectForKey:@"itemKey"];
        _valueInDollars = [aDecoder decodeIntForKey:@"valueInDollars"];
        _thumbNail = [aDecoder decodeObjectForKey:@"thumbnail"];


    }
    return self;
}



- (id) initWithItemName:(NSString *)name
         valueInDollars: (int) value
           serialNumber: (NSString *) sNumber;
    {

    self = [super init];


    //Give the instance variables initial values
    [self setItemName:name]; //point to self since its the initializer of the object
    [self setSerialNumber:sNumber];
    [self setValueInDollars:value];
    _dateCreated = [[NSDate alloc]init];

    NSUUID *uuid = [[NSUUID alloc] init];
    NSString *key = [uuid UUIDString];
    _itemKey = key;

    return self; //return self so that you can assign it to a variable
}

EDIT - Here is the rest of the implementation for the BNRItem. Namely, a method to randomize the properties of the BNRItem and another to give it a thumbnail image

//Creates a BNRItem instance with a random name, random value and random serial number
+ (id)randomItem {
//Create an array of three adjectives
NSArray *randomAdjectiveList = [NSArray arrayWithObjects:@"John", @"Kyle", @"Jerry", nil];

//Create an array of three nouns
NSArray *randomNounList = [NSArray arrayWithObjects:@"Cheese", @"Meat", @"Vegetables",    
nil];

NSInteger adjectiveIndex = rand() % [randomAdjectiveList count];
NSInteger nounIndex = rand() % [randomNounList count];

NSString *randomName = [NSString stringWithFormat:@"%@ %@", [randomAdjectiveList   
objectAtIndex:adjectiveIndex], [randomNounList objectAtIndex:nounIndex]];

int randomValue = rand () % 100;

NSString *randomSerialNumber = [NSString stringWithFormat:@"%c%c%c%c%c",
                                '0' + rand() % 10,
                                'A' + rand() % 26,
                                '0' + rand() % 10,
                                'A' + rand() % 26,
                                '0' + rand() % 10 ];

BNRItem *newItem = [[self alloc] initWithItemName:randomName
                                   valueInDollars:randomValue
                                     serialNumber:randomSerialNumber];

return newItem;

}




- (void) setThumbNailFromImage:(UIImage *)image
{
CGSize origImageSize = image.size;

CGRect newRect = CGRectMake(0, 0, 40, 40);

//Figure out a scaling ratio to make sure we maintain the same aspect ratio
float ratio = MAX(newRect.size.width / origImageSize.width, newRect.size.height /  
origImageSize.height);

//Createa a transparent bitmap context with a scaling factor equal to that of the screen

UIGraphicsBeginImageContextWithOptions(newRect.size, NO, 0.0);

//Create a path that is a rounded rectangle
UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:newRect cornerRadius:5.0];

//Make all subsequent drawing clip to this rounded rectangle
[path addClip];

//Center the image in the thumbnail rectangle
CGRect projectRect;
projectRect.size.width = ratio * origImageSize.width;
projectRect.size.height  = ratio * origImageSize.height;
projectRect.origin.x = (newRect.size.width - projectRect.size.width) / 2.0;
projectRect.origin.y = (newRect.size.height - projectRect.size.height);


//Draw the image on it
[image drawInRect:projectRect];

//Get the image from the image context; keep it as our thumbnail
UIImage *smallImage = UIGraphicsGetImageFromCurrentImageContext();
self.thumbNail = smallImage;

//Clea image context resources; we're done
UIGraphicsEndImageContext();


}

The UITableViewCell was created with a xib and has 4 outlets (3 labels and one image).

#import <Foundation/Foundation.h>

@interface BNRItemCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UILabel *serialNumberLabel;
@property (weak, nonatomic) IBOutlet UILabel *valueLabel;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UIImageView *thumbnailView;

@end

I haven't learned Core Data yet but it's coming up, the problem is that I need to get what I have working so that I can keep modifying it with the textbook instructions. Any help's appreciated!

You have an extra ; after serialNumber: (NSString *) sNumber; which causes the error. Remove it & try again.

Try this may be it will help you

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{

 BNRItemCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BNRItemCell"  forIndexPath:indexPath];
if (cell == nil)
{
 cell = [[BNRItemCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}

NSArray *items = [[BNRItemStore sharedStore] allItems];
//Set BNRItem instances to equal a given object in the items[] array
BNRItem *item = [items objectAtIndex:indexPath.row];// try this as well
cell.nameLabel.text = [NSString stringWithFormat:@"%@",item.itemName];  // must try this
cell.serialNumberLabel.text = item.serialNumber;
cell.valueLabel.text = [NSString stringWithFormat:@"$%d", item.valueInDollars];
cell.thumbnailView.image = item.thumbNail;

return cell;

}

I ran into that problem as well. I went into the BNRItemCell.xib file and opened up the document outliner, right clicked on some of the labels in the view trees to check out the reference outlets. I notices that they were hooked up to the file's Owner in the xib as well as the IBOutlet's in the BNRItemCell.h file. I unhooked them from the File's Owner and it fixed the problem. Not sure if that is your issue, but check it out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM