简体   繁体   中英

iOS: Object returning *nil description* after alloc and init

Let me preface this question by saying that I believe it to be a memory management mistake on my end. I just can't seem to figure out why it is happening.

I have a viewcontroller and a model class named Part .

#import <Foundation/Foundation.h>

@interface Part : NSObject

@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *partType;
@property (nonatomic, strong) NSString *description;
@property (nonatomic, strong) NSNumber *price;

- (id)initWithName:(NSString *)name AndType:(NSString *)type;

@end

In the view controller I have a property set as follows:

@property (nonatomic, strong) Part *part;

In the init function of ViewController I create some static arrays and create objects out of them:

- (id)init {
    self = [super init];

    self.partList = [[NSMutableArray alloc] init];

    NSArray *inputArray = @[@"Part1",
    @"Part2",
    @"Part3",
    @"Part4",
    @"Part5",
    @"Part6",
    @"Part7",
    @"Part8"];

    NSString *tempType = @"PartCategory";

    // Add dummy static data
    for (int i = 0; i < [inputArray count]; i++) {
        Part *partInput = [[Part alloc] initWithName:[inputArray objectAtIndex:i] AndType:tempType];
        //partInput.name = [inputArray objectAtIndex:i];
        //partInput.partType = tempType;
        NSLog(@"Inserting Part %@", partInput);
        [self.partList addObject:partInput];
    }

    return self;
}

The NSLog I call in that loop returns Inserting Part *nil description* for every part. I just can't track down what is happening here.

EDIT: Here is the initWithName method from Part that the controller uses:

- (id)initWithName:(NSString *)name AndType:(NSString *)type {
    if(self = [super init]) {
        self.name = name;
        self.partType = type;
    }

    return self;
}

When using %@ to print NSObject, it calls debugDescription that by default calling the description method of that object and your Part object always have nil description.

You better solve this by changing the description property name to something else, because it conflicts with the description method of NSObject .

See also: NSObject description and debugDescription

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