Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I alloc/init - get "Assigning retained object to unsafe property" warning?

I am new to ARC, and I have an object which has some internal classes as members. On the init method I want to allocate new objects for them.

ClassA.h

#import "ClassB.h"
@interface ClassA : NSObject
@property (assign) ClassB *member;
@end

ClassB.h

@interface ClassB : NSObject
@property (assign) NSString *name;
@end

ClassA.m

@synthesize member = _member;
-(id)init
{
    _member = [[ClassB alloc] init];
}

But I get "Assigning retained object to unsafe property" errors. I searched over the inter webs, and see no other information on this specific warning. It compiles, but gets a runtime bad access exception.

like image 917
Ronaldo Nascimento Avatar asked Nov 25 '11 13:11

Ronaldo Nascimento


1 Answers

The immediate problem is that you're assigning the object to a member marked weak, which means that the object won't have a strong reference and will be deallocated immediately. Using strong or retain instead of weak or assign will fix that.

A larger problem with your -init method is that it doesn't call [super init], and it doesn't return anything. At minimum, your -init should look like this:

-(id)init
{
    self = [super init];
    if (self != nil) {
        self.member = [[ClassB alloc] init];
    }
    return self;
}
like image 182
Caleb Avatar answered Nov 09 '22 08:11

Caleb