3

I wanted to programmatically add myView to parent view. But it doesn't show up on screen. What's wrong with the code?

@interface ViewController ()
@property (nonatomic,weak) UIView *myView;
@end

@implementation ViewController
@synthesize myView = _myView;

- (void)viewDidLoad
{
    [super viewDidLoad];
    CGRect viewRect = CGRectMake(10, 10, 100, 100);
    self.myView = [[UIView alloc] initWithFrame:viewRect];
    self.myView.backgroundColor = [UIColor redColor];
    [self.view addSubview:self.myView];
}
Philip007
  • 3,190
  • 7
  • 46
  • 71
  • try `@property (nonatomic,strong) UIView *myView;` – janusfidel Aug 30 '12 at 10:49
  • Thanks,that works. But I wonder why? Setting property to strong makes myView is retained twice, both by controller (self) and self.view. Is that correct? Why weak don't work? – Philip007 Aug 30 '12 at 10:52
  • NO, it's the only subview. It seems that property is indeed relevant, because changing weak to strong fix the problem. – Philip007 Aug 30 '12 at 10:56
  • 1
    Alright, there's some interesting magic: http://stackoverflow.com/a/9747451/792677 – A-Live Aug 30 '12 at 10:58
  • property attribute tells the compiler how your object be treated. here is a link that has good information regarding weak and strong. http://www.raywenderlich.com/5677/beginning-arc-in-ios-5-part-1 – janusfidel Aug 30 '12 at 11:01
  • Thanks @A-Live, that's exactly the explanation I need. – Philip007 Aug 30 '12 at 11:24

2 Answers2

8

Replace

@property (nonatomic,weak) UIView *myView;

with

@property (strong, nonatomic) UIView *myView;

and it should work :)

user1629713
  • 146
  • 4
2
@interface ViewController ()

@end

@implementation ViewController

UIView *myView;

-(void)viewDidLoad
{
    [super viewDidLoad];

    CGRect viewRect = CGRectMake(10, 10, 100, 100);

    myView = [[UIView alloc] initWithFrame:viewRect];

    myView.backgroundColor = [UIColor redColor];

    [self.view addSubview:myView];
}

try this it will work…

Regexident
  • 29,441
  • 10
  • 93
  • 100