iOS custom object initialization Error

1.6k views Asked by At

I have a custom object ProductCategory.

.h file:

#import <Foundation/Foundation.h>

@interface ProductCategory : NSObject

@property int productCategoryId;
@property NSString *name;
@property NSArray *children;
@property int parentCategoryId;


- (id)initWithId:(int)productCategoryId name:(NSString*)name;

- (id)initWithId:(int)productCategoryId name:(NSString*)name children:(NSArray*)chidren parentCategoryId:(int)parentCategoryId;

@end

.m file:

#import "ProductCategory.h"

@implementation ProductCategory

- (id)init {
    if((self = [super init])) {
        self.parentCategoryId = 0;
    }

    return self;
}

- (id)initWithId:(int)productCategoryId name:(NSString*)name {
    if((self = [super init])) {
        self.productCategoryId = productCategoryId;
        self.name = name;
        self.parentCategoryId = 0;
    }

    return self;
}


- (id)initWithId:(int)productCategoryId name:(NSString*)name children:(NSArray*)chidren parentCategoryId:(int)parentCategoryId {
    if((self = [super init])) {
        self.productCategoryId = productCategoryId;
        self.name = name;
        self.children = chidren;
        self.parentCategoryId = parentCategoryId;
    }

    return self;
}

@end

It's just a normal object, I have done this 100000 times. The problem is, sometimes the instance of this object returns "0 objects" and sometimes returns the correct object.

For example, if I do this ProductCategory *category = [[ProductCategory alloc]init]; sometimes it returns a ProductCategory instance, and sometimes it returns "0 objects" so I cannot assign any value to this object.

enter image description here

I guess it should be something really stupid but I don't see it.

2

There are 2 answers

0
zevarito On

The way to fix it:

Restart XCode.

Why it happen?:

Apple should answer this question.

It seems a garbage in memory issue after a period of time using XCode.

Workarounds if you get trap there

@HotLicks is right about the advising of use NSLog and po to be sure about the state of that object.

Also you can invoke methods and read properties of the object in question by using expression command in debugger window after a breakpoint.

0
ctd On

zevarito is on the right track. A bit more seems to solve the long-irritating problem:

Close the project.

Xcode -> Window -> Projects For the project in question (and all others is probably a good housecleaning idea), click Derived Data -> Delete.

Close Xcode. Close Simulator.

Restart Xcode and resume what you were doing.