开发者

iOS - Objects being released?

开发者 https://www.devze.com 2023-04-13 09:22 出处:网络
I have the following piece of code: Dummy *dummy = [[Dymmy alloc] initWithDictionary:dummyData]; DummyTableItem *dummyTableItem = [DummyTableItem itemWithDummy: dummy];

I have the following piece of code:

Dummy *dummy = [[Dymmy alloc] initWithDictionary:dummyData];
DummyTableItem *dummyTableItem = [DummyTableItem itemWithDummy: dummy];
[_data addObject: dummyTableItem];

The init functions are as follows:

+ (id) itemWithDummy: (Dummy *) dummy {
  DummyTableItem *item = [[[self alloc] init] autorelease];
  item.dummy = dummy;
  return item;
}

- (id) init {
 开发者_如何学Python self = [super init];
  if( self ) {
    dummy = nil;
  }
  return self;
}

with dummy declared as (nonatomic, retain)

And Dummy:

@synthesize name=_name;

- (id) initWithDictionary: (NSDictionary *) dictionary {
  self = [super init];

  if( self != nil ) {
    if( [dictionary objectForKey:@"name"] )
  _name = [dictionary objectForKey:@"name"];
  }

  return self;
}

with name again declared as (nonatomic, retain)

When I am trying to access later on the dummyTableItem.dummy.name to set it to a UILabel I am getting a "-[CFString isEqualToString:]: message sent to deallocated instance 0x5b37a10"

Am I doing something completely wrong with the retained objects? What am I missing here? Also in the first part of code should I release the dummyTableItem after adding it to _data (which is an NSMutableArray?)


This should solve the problem inside Dummy's @implementation :

@synthesize name=_name;

- (id) initWithDictionary: (NSDictionary *) dictionary {
  self = [super init];
  if (self) {
    _name = [[dictionary objectForKey:@"name"] retain]; //retain it :)
  }
  return self;
}

Since you declared name as retain you should own it (That is why I added retain when assigning it). Furthermore, you don't need to check if( [dictionary objectForKey:@"name"] ) because _name = [nil retain]; is nil anyways :)

0

精彩评论

暂无评论...
验证码 换一张
取 消